根据属性过滤对象数组
问题:
你有一个真实的数组房地产对象并希望根据特定属性(例如价格、平方英尺、床位数量和数量)对其进行过滤
解决方案:
要过滤数组,可以使用 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; });
说明:
过滤器方法采用一个测试每个元素的回调函数在数组中。如果测试返回 true,则该元素将包含在新数组中。在这种情况下,回调函数会检查 home 对象是否满足指定条件,如果满足则返回 true。
实例:
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);
以上是如何根据属性过滤房地产家庭对象数组?的详细内容。更多信息请关注PHP中文网其他相关文章!