根據屬性過濾物件陣列
問題:
你有一個真實的數組房地產對象並希望根據特定屬性(例如價格、平方英尺、床位數量和數量)對其進行過濾
解決方案:
要過濾數組,可以使用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中文網其他相關文章!