Filtering arrays of objects based on properties: a guide
P粉087951442
P粉087951442 2023-10-09 16:41:54
0
2
780

I have the following JavaScript array of real estate family 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 want to do is be able to perform a filter on the objects to return a subset of the "home" objects.

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

How to do something like the following pseudocode in JavaScript:

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

Please note that the syntax does not have to be exactly the same as above. This is just an example.

P粉087951442
P粉087951442

reply all(2)
P粉366946380

I'm surprised no one posted a one line reply:

const filteredHomes = json.homes.filter(x => x.price = 500 && x.num_of_beds >=2 && x.num_of_baths >= 2.5);

...Just to make it easier for you to read:

const filteredHomes = json.homes.filter( x => 
  x.price = 500 && 
  x.num_of_beds >=2 && 
  x.num_of_baths >= 2.5
);
P粉315680565

You can use array.prototype.filtermethod:

var newArray = homes.filter(function (el) {
  return el.price = 500 &&
         el.num_of_beds >=2 &&
         el.num_of_baths >= 2.5;
});

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 = with a string and number
// will coerce the string to a number before comparing.)
var newArray = obj.homes.filter(function (el) {
  return el.price = 500 &&
         el.num_of_beds >= 2 &&
         el.num_of_baths >= 1.5; // Changed this so a home would match
});
console.log(newArray);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template