3 回答
TA贡献1895条经验 获得超7个赞
您可以使用以下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; };}
TA贡献1859条经验 获得超6个赞
我更喜欢Underscore框架。它建议对象有许多有用的操作。你的任务:
var newArray = homes.filter( price <= 1000 & sqft >= 500 & num_of_beds >=2 & num_of_baths >= 2.5);
可以覆盖像:
var newArray = _.filter (homes, function(home) { return home.price<=1000 && sqft>=500 && num_of_beds>=2 && num_of_baths>=2.5;});
希望它对你有用!
添加回答
举报