如何根据属性过滤对象数组?

新手上路,请多包涵

我有以下房地产家庭对象的 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”对象的子集。

例如,我希望能够根据: pricesqftnum_of_bedsnum_of_baths 进行过滤。

如何在 JavaScript 中执行某些操作,如下面的伪代码:

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

请注意,语法不必与上面完全相同。这只是一个例子。

原文由 JGreig 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 774
2 个回答

您可以使用 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;
 };
 }

原文由 Christian C. Salvadó 发布,翻译遵循 CC BY-SA 4.0 许可协议

我很惊讶没有人发布单行回复:

 const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

…这样您就可以更轻松地阅读它:

 const filteredHomes = json.homes.filter( x =>
  x.price <= 1000 &&
  x.sqft >= 500 &&
  x.num_of_beds >=2 &&
  x.num_of_baths >= 2.5
);

原文由 Lou Bagel 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏