問題:如何依照巢狀值過濾物件陣列?
輸入:
<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>
所需輸出:
<code class="javascript">let filteredArray = [ { "name": "a", "subElements": [ {"surname": 1} ] }, { "name": "b", "subElements": [ {"surname": 1} ] } ];</code>
初始嘗試: >
<code class="javascript">let filteredArray = arrayOfElements.filter((element) => element.subElements.some((subElement) => subElement.surname === 1));</code>
問題:此方法傳回具有所有姓氏的對象,而不是將它們修剪掉。
解:
<code class="javascript">arrayOfElements.map((element) => { return {...element, subElements: element.subElements.filter((subElement) => subElement.surname === 1)} })</code>
說明:
以上是如何根據巢狀值使用陣列過濾物件數組?的詳細內容。更多資訊請關注PHP中文網其他相關文章!