array filter object based on key value in javascript

To filter an array of objects based on a key value, you can use the Array.filter() method along with a callback function that checks each object's key value. Here's an example:

index.tsx
const data = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Jane'},
  {id: 3, name: 'Bob'}
];

const filteredData = data.filter(obj => obj.name === 'Jane');

console.log(filteredData);
// Output: [{id: 2, name: 'Jane'}]
217 chars
11 lines

In this example, we have an array of objects data with each object having an id and a name key. We want to filter all the objects where the name is equal to 'Jane'. We pass a callback function to the Array.filter() method that checks if the name key matches our filter value ('Jane'). The filter() method returns a new array (filteredData) with all objects that pass our filter.

gistlibby LogSnag