Javascript: How to filter object array based on attributes?

Posted by JGreig on Stack Overflow See other posts from Stack Overflow or by JGreig
Published on 2010-04-27T14:42:39Z Indexed on 2010/04/27 14:53 UTC
Read the original article Hit count: 192

I have the following JavaScript JSON array of real estate home objects:

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;

What I would like to do is be able to perform a filter on the object to return a subset of "home" objects.

For example, I want to be able to filter based on: price, sqft, num_of_beds, and num_of_baths.

Question: How can I perform something in javascript like the pseudo-code below:

var newArray = homes.filter(
price <= 1000 & 
sqft >= 500 & 
num_of_beds >=2 & 
num_of_baths >= 2.5);

Note, the syntax does not have to be exactly like above. This is just an example.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery