Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-10-26 12:14:02
Original
799 people have browsed it

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

Filtering Array of Objects with Multiple Conditions in JavaScript

To simplify an array of objects based on multiple conditions, the filter() method can be effectively utilized. This method allows you to narrow down the original array by selecting only those elements that meet specific criteria.

Consider the following array of users:

<code class="javascript">var users = [
    {
        name: 'John',
        email: '[email&#160;protected]',
        age: 25,
        address: 'USA'
    },
    {
        name: 'Tom',
        email: '[email&#160;protected]',
        age: 35,
        address: 'England'
    },
    {
        name: 'Mark',
        email: '[email&#160;protected]',
        age: 28,
        address: 'England'
    }
];</code>
Copy after login

Suppose you wish to filter this array based on both the address and name properties. To achieve this, you can utilize the following approach:

<code class="javascript">var filter = {
  address: 'England',
  name: 'Mark'
};

users = users.filter(function(item) {
  for (var key in filter) {
    if (item[key] === undefined || item[key] != filter[key])
      return false;
  }
  return true;
});</code>
Copy after login

In this case, the filter object defines the conditions to be met, i.e., the address being 'England' and the name being 'Mark.' The filter() method then iterates over each user object and checks if all the conditions in the filter object are satisfied. Only those objects that meet all the conditions are retained in the filtered array.

By using this approach, you can effectively narrow down your array based on multiple criteria, providing a flexible and efficient way to select specific objects from a larger dataset.

The above is the detailed content of How to Filter an Array of Objects with Multiple Conditions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!