我有以下JavaScript数组的房地产家对象:

var json = {
    'homes': [{
            "home_id": "1",
            "price": "925",
            "sqft": "1100",
            "num_of_beds": "2",
            "num_of_baths": "2.0",
        }, {
            "home_id": "2",
            "price": "1425",
            "sqft": "1900",
            "num_of_beds": "4",
            "num_of_baths": "2.5",
        },
        // ... (more homes) ...     
    ]
}

var xmlhttp = eval('(' + json + ')');
homes = xmlhttp.homes;

我想做的是能够对对象执行筛选,以返回“home”对象的子集。

例如,我希望能够基于:price、sqft、num_of_beds和num_of_baths进行过滤。

我如何在JavaScript中执行下面的伪代码:

var newArray = homes.filter(
    price <= 1000 & 
    sqft >= 500 & 
    num_of_beds >=2 & 
    num_of_baths >= 2.5 );

注意,语法不必完全像上面那样。这只是一个例子。


当前回答

我看到有一种情况没有被覆盖,也许有人会像我一样寻找匹配的情况。情况下,当有人想要过滤属性值,这是字符串或数字使用过滤作为“where matches”条件,让我们说通过城市名称等。换句话说,就像Query:返回ALL homes数组WHERE city = "Chicago"。解决方法很简单:

  const filterByPropertyValue = (cityName) => {
    let filteredItems = homes.filter((item) => item.city === cityName);
    console.log("FILTERED HOMES BY CITY:", filteredItems);
  }

如果你需要通过编程或在HTML中循环/映射数组或通过提供'city'值来触发它(你也可以提供数组,只需要在函数中添加它来重用函数):

            <button
              onClick={() => {
                filterByPropertyValue("Chicago");
              }}
            >
              Chicago Homes Only
            </button>

假设JSON添加了城市属性:

'homes': [{
        "home_id": "1",
        "price": "925",
        "sqft": "1100",
        "num_of_beds": "2",
        "num_of_baths": "2.0",
        "city":"Chicago",
    }, {
        "home_id": "2",
        "price": "1425",
        "sqft": "1900",
        "num_of_beds": "4",
        "num_of_baths": "2.5",
        "city":"Chicago",
    },
    // ... (more homes) ...     
    {
        "home_id": "3-will-be-matched",
        "price": "925",
        "sqft": "1000",
        "num_of_beds": "2",
        "num_of_baths": "2.5",
        "city":"Atlanta",
    },
]

其他回答

这里是工作提琴,在IE8使用jquery MAP函数工作良好

http://jsfiddle.net/533135/Cj4j7/

json.HOMES = $.map(json.HOMES, function(val, key) {
    if (Number(val.price) <= 1000
            && Number(val.sqft) >= 500
            && Number(val.num_of_beds) >=2
            && Number(val.num_of_baths ) >= 2.5)
        return val;
});
const state.contactList = [{
    name: 'jane',
    email: 'jane@gmail.com'
  },{},{},...]

const fileredArray = state.contactsList.filter((contactItem) => {
  const regex = new RegExp(`${action.payload}`, 'gi');
  return contactItem.nameProperty.match(regex) || 
    contactItem.emailProperty.match(regex);
});


// contactList: all the contacts stored in state
// action.payload: whatever typed in search field

你可以使用Array.prototype.filter方法:

var newArray = homes.filter(function (el) {
  return el.price <= 1000 &&
         el.sqft >= 500 &&
         el.num_of_beds >=2 &&
         el.num_of_baths >= 2.5;
});

生活例子:

var obj = { 'homes': [{ "home_id": "1", "price": "925", "sqft": "1100", "num_of_beds": "2", "num_of_baths": "2.0", }, { "home_id": "2", "price": "1425", "sqft": "1900", "num_of_beds": "4", "num_of_baths": "2.5", }, // ... (more homes) ... ] }; // (Note that because `price` and such are given as strings in your object, // the below relies on the fact that <= and >= with a string and number // will coerce the string to a number before comparing.) var newArray = obj.homes.filter(function (el) { return el.price <= 1000 && el.sqft >= 500 && el.num_of_beds >= 2 && el.num_of_baths >= 1.5; // Changed this so a home would match }); console.log(newArray);

该方法是新的ECMAScript第5版标准的一部分,可以在几乎所有现代浏览器中找到。

对于IE,为了兼容性,你可以包含以下方法:

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this) {
        var val = this[i];
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }
    return res;
  };
}
**

The simplest way to search a specific value in an Array of Object
--------------------------------------------------------------------

filter() -> uses a callback function the return value of which decides what will be returned in the filtered array. If the return value is true, the item is included in the resultant array.

includes() -> searches for something in an array of items using == equality
**

       const words = [{id:1,name:"tim"},{id:2,name:"morgon"}]
        
          function searchHandler(enteredString){
          const formatedString = enteredString.toLowerCase();
          const result = words.filter(data=> data?.name?.includes(formatedString));
          console.log(result);
    }
const y = 'search text';
const a = [{key: "x", "val: "y"},  {key: "d", "val: "z"}]
const data = a.filter(res => {
        return(JSON.stringify(res).toLocaleLowerCase()).match(y.toLocaleLowerCase());
});