Categories
JavaScript Answers

How to filter a complex JSON object using JavaScript?

Spread the love

Sometimes, we want to filter a complex JSON object using JavaScript.

In this article, we’ll look at how to filter a complex JSON object using JavaScript.

How to filter a complex JSON object using JavaScript?

To filter a complex JSON object using JavaScript, we can use the array filter method.

For instance, we write:

const obj = {
  "Lofts": "none",
  "Maisons": "2",
  "homes": [{
    "home_id": "1",
    "price": "925",
    "num_of_beds": "2"
  }, {
    "home_id": "2",
    "price": "1425",
    "num_of_beds": "4",
  }, {
    "home_id": "3",
    "price": "333",
    "num_of_beds": "5",
  }]
};

const filtered = obj.homes.filter((a) => {
  return a.home_id === '2';
});
console.log(filtered)

to call obj.homes.filter with a callback to return an array with the object with home_id property equal to 2.

As a result, filtered is

[{
  home_id: "2",
  num_of_beds: "4",
  price: "1425"
}]

Conclusion

To filter a complex JSON object using JavaScript, we can use the array filter method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *