Home >Web Front-end >JS Tutorial >How to Filter an Array of Objects by Multiple Conditions in JavaScript?
Simplifying Array of Objects Based on Multiple Filter Conditions in JavaScript
Question:
How can I simplify an array of objects based on multiple filter conditions in JavaScript? For instance, with the following array:
var users = [ { name: 'John', email: '[email protected]', age: 25, address: 'USA' }, { name: 'Tom', email: '[email protected]', age: 35, address: 'England' }, { name: 'Mark', email: '[email protected]', age: 28, address: 'England' } ];
And filter object:
var filter = { address: 'England', name: 'Mark' };
I want to filter all users by both address and name. Currently, my function adds all users with the matching address in the first iteration and only the last user with the matching name in the second iteration. However, I need to filter by both conditions simultaneously.
Answer:
To filter an array of objects based on multiple conditions, you can utilize the following approach:
users = users.filter(function(item) { for (var key in filter) { if (item[key] === undefined || item[key] != filter[key]) return false; } return true; });
This code iterates through both the array of objects and the filter object, ensuring that each object in the array matches all the conditions specified in the filter. The item[key] and filter[key] comparison checks whether the value of the property key in the object item matches the corresponding value in the filter object. If any of the conditions fail, the filter function returns false, excluding that object from the filtered result. Otherwise, it returns true, indicating that the object meets all the filter conditions.
By applying this approach, you can effectively filter an array of objects based on multiple criteria, ensuring that only the objects that satisfy all the conditions are included in the result.
The above is the detailed content of How to Filter an Array of Objects by Multiple Conditions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!