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

How to Filter an Array of Objects Based on a Nested Value Array?

DDD
Release: 2024-10-30 23:46:30
Original
794 people have browsed it

How to Filter an Array of Objects Based on a Nested Value Array?

Filtering Array of Objects with Nested Value Arrays

Filtering an array of objects based on a nested value can be a common challenge. To address this, let's examine the provided fiddle:

Input Array:

let arrayOfElements = [
    {
        "name": "a",
        "subElements": [
            {"surname": 1},
            {"surname": 2}
        ]
    },
    {
        "name": "b",
        "subElements": [
            {"surname": 3},
            {"surname": 1}
        ]
    },
    {
        "name": "c",
        "subElements": [
            {"surname": 2},
            {"surname": 5}
        ]
    }
];
Copy after login

Desired Output:

let filteredArray = [
    {
        "name": "a",
        "subElements": [
            {"surname": 1}
        ]
    },
    {
        "name": "b",
        "subElements": [
            {"surname": 1}
        ]
    }
];
Copy after login

Original Filtering Approach:

let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === 1));
Copy after login

While this formula does filter the array, it returns objects with all surnames instead of removing them.

Improved Filtering Method:

arrayOfElements.map((element) => {
  return {...element, subElements: element.subElements.filter((subElement) => subElement.surname === 1)}
})
Copy after login

This method utilizes the spread operator (...) to create a new object for each element in the array. Inside the new object, the subElements property is filtered to include only those with the desired surname value (surname === 1).

Using this approach, you can filter arrays with arbitrarily deep nested objects by iteratively applying the map function to access and filter the desired data.

The above is the detailed content of How to Filter an Array of Objects Based on a Nested Value Array?. 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
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!