Mám následující pole JavaScriptu objektů realitních domů:
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;
Co bych chtěl udělat, je umět provést filtr na objekt, který vrátí podmnožinu „domovských“ objektů.
Například chci mít možnost filtrovat na základě:price
, sqft
, num_of_beds
a num_of_baths
.
Jak mohu provést něco v JavaScriptu, jako je níže uvedený pseudokód:
var newArray = homes.filter( price <= 1000 & sqft >= 500 & num_of_beds >=2 & num_of_baths >= 2.5 );
Všimněte si, že syntaxe nemusí být přesně jako výše. Toto je jen příklad.
Odpověď
Můžete použít Array.prototype.filter
metoda:
var newArray = homes.filter(function (el) { return el.price <= 1000 && el.sqft >= 500 && el.num_of_beds >=2 && el.num_of_baths >= 2.5; });
Živý příklad:
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);
Tato metoda je součástí nového standardu ECMAScript 5th Edition a lze ji nalézt téměř ve všech moderních prohlížečích.
Pro IE můžete zahrnout následující metodu kompatibility:
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; }; }