Ask Your Question
3

How can you apply filtering to an object that is nested in Javascript?

asked 2022-05-10 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-06-27 02:00:00 +0000

nofretete gravatar image

To apply filtering to an object that is nested in JavaScript, you can use a combination of array methods such as filter(), map(), and reduce(). Here's an example of how to filter an array of objects based on a nested property:

const data = [
  { name: 'John', age: 30, address: { city: 'New York', state: 'NY' } },
  { name: 'Jane', age: 25, address: { city: 'Los Angeles', state: 'CA' } },
  { name: 'Bob', age: 40, address: { city: 'Chicago', state: 'IL' } },
];

const filteredData = data.filter((item) => item.address.city === 'New York');

console.log(filteredData);
// Output: [{ name: 'John', age: 30, address: { city: 'New York', state: 'NY' } }]

In this example, we use the filter() method to iterate through the array and return only the objects where the value of the city property in the nested address object is equal to 'New York'.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-10 11:00:00 +0000

Seen: 9 times

Last updated: Jun 27 '22