Home  >  Article  >  Web Front-end  >  How to Filter an Array of Objects by Multiple Conditions in JavaScript?

How to Filter an Array of Objects by Multiple Conditions in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 22:07:29857browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn