Filter array of object by key value

Assuming that you have an array of objects and each object has a key called “status”, you can filter the array to get only the objects where the value of “status” is 0 using the filter method in JavaScript.

Here’s an example code snippet:

const myArray = [
  {id: 1, status: 0},
  {id: 2, status: 1},
  {id: 3, status: 0},
  {id: 4, status: 1},
];

const filteredArray = myArray.filter(obj => obj.status === 0);

console.log(filteredArray);
// Output: [{id: 1, status: 0}, {id: 3, status: 0}]

In this example, we have an array called myArray that contains four objects. We then use the filter method to create a new array called filteredArray that only contains the objects where the value of “status” is 0.

The filter method takes a function as an argument that returns true for each element that should be included in the filtered array, and false for each element that should be excluded. In this case, the function checks if the value of “status” is equal to 0 for each object, and only returns true for those that match.

Related Posts

Leave a Reply

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