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>
Desired Output:
<code class="javascript">let filteredArray = [ { "name": "a", "subElements": [ {"surname": 1} ] }, { "name": "b", "subElements": [ {"surname": 1} ] } ];</code>
Initial Attempt:
<code class="javascript">let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === 1));</code>
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>
Explanation:
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!