Home > Article > Web Front-end > 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} ] } ];
Desired Output:
let filteredArray = [ { "name": "a", "subElements": [ {"surname": 1} ] }, { "name": "b", "subElements": [ {"surname": 1} ] } ];
Original Filtering Approach:
let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === 1));
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)} })
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!