How to filter object array based on attributes?
Solution 1:
You can use the Array.prototype.filter
method:
var newArray = homes.filter(function (el) {
return el.price <= 1000 &&
el.sqft >= 500 &&
el.num_of_beds >=2 &&
el.num_of_baths >= 2.5;
});
Live Example:
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);
This method is part of the new ECMAScript 5th Edition standard, and can be found on almost all modern browsers.
For IE, you can include the following method for compatibility:
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;
};
}
Solution 2:
I'm surprised no one has posted the one-line response:
const filteredHomes = json.homes.filter(x => x.price <= 1000 && x.sqft >= 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);
...and just so you can read it easier:
const filteredHomes = json.homes.filter( x =>
x.price <= 1000 &&
x.sqft >= 500 &&
x.num_of_beds >=2 &&
x.num_of_baths >= 2.5
);
Solution 3:
You can try using framework like jLinq - following is a code sample of using jLinq
var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();
For more information you can follow the link http://www.hugoware.net/projects/jlinq