问题:如何根据嵌套值过滤对象数组?
输入:
<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中文网其他相关文章!