How to useArray.filter() and Object.entries() in Javascript
Utilizing Array.filter()
along with Object.entries()
provides a concise method of filtering objects based on multiple properties. We are filtering the elements of the array based on the given condition and by the use of the Object.entries we are adding the filtered elements into it.
Example: This example shows the use of Array.filter() and Object.entries() method for filtering the array and adding element to to the object.
JavaScript
const data = [ { id: 1, name: 'John' , age: 25 }, { id: 2, name: 'Jane' , age: 30 }, { id: 3, name: 'Doe' , age: 25 }, ]; // Filtering based on multiple properties // using Array.filter() and Object.entries() const filterConditions = { age: 25, name: 'John' }; const filteredData = data.filter(item => Object.entries(filterConditions) .every(([key, value]) => item[key] === value) ); console.log(filteredData); |
Output
[ { id: 1, name: 'John', age: 25 } ]
How to Filter an Array of Objects Based on Multiple Properties in JavaScript ?
Filtering an array of objects based on multiple properties is a common task in JavaScript. It allows us to selectively extract items from an array that satisfy specific conditions. We will explore different approaches to achieve this task.
These are the following approaches:
Table of Content
- Using the filter() Method
- Using a for Loop
- Using Array.from() and filter()
- Using reduce() method
- Using forEach() and filter()
- Using Array.filter() and Object.entries()
- Using Array.filter() and Object.keys()