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

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

DDD
Release: 2024-10-29 03:08:02
Original
165 people have browsed it

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

Filtering Array of Objects with Arrays Based on Nested Value

Question: How do I filter an array of objects based on a nested value?

Input:

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

Desired Output:

<code class="javascript">let filteredArray = [
    {
        "name": "a",
        "subElements": [
            {"surname": 1}
        ]
    },
    {
        "name": "b",
        "subElements": [
            {"surname": 1}
        ]
    }
];</code>
Copy after login

Initial Attempt:

<code class="javascript">let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === 1));</code>
Copy after login

Issue: This approach returns objects with all surnames instead of trimming them away.

Solution:

<code class="javascript">arrayOfElements.map((element) => {
    return {...element, subElements: element.subElements.filter((subElement) => subElement.surname === 1)}
})</code>
Copy after login

Explanation:

  • This approach uses the map() method to iterate over the arrayOfElements.
  • For each element, it spreads its properties into a new object.
  • It then uses filter() on the subElements array to retain only those that meet the condition (surname === 1).
  • The filtered subElements are then used to override the original subElements array.

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