JavaScript:基于子数组值过滤三层嵌套数组并筛选子元素
问题描述
我有一个三层嵌套数组,需要根据子数组的checked值过滤数据:
- 过滤掉没有任何已勾选子元素的父元素(已实现)
- 同时要过滤掉父元素下
checked为false的子元素(未实现)
数据结构
{ "id": 1, "grandparent": "Timmy", "parents": [ { "id": 1, "parent": "Johnny", "children": [ { "id": 1, "child": "Sam", "checked": true }, { "id": 1, "child": "Ted", "checked": false } ] }, { "id": 2, "parent": "Jessica", "children": [ { "id": 1, "child": "Sam", "checked": false } ] } ] }
现有代码
grandparents.value = value.value.map((el) => ({ ...el, parents: el.components.filter((parent) => parent.children?.some((child) => child.checked)) }))
注:代码里的el.components应为el.parents,属于笔误。
当前结果(不符合预期)
{ "id": 1, "grandparent": "Timmy", "parents": [ { "id": 1, "parent": "Johnny", "children": [ { "id": 1, "child": "Sam", "checked": true }, { "id": 1, "child": "Ted", "checked": false } ] } ] }
期望结果
{ "id": 1, "grandparent": "Timmy", "parents": [ { "id": 1, "parent": "Johnny", "children": [ { "id": 1, "child": "Sam", "checked": true } ] } ] }
解决方案
你需要在过滤父元素的同时,对保留下来的父元素的children数组也做一次过滤,只保留checked: true的子元素。修改后的代码如下:
grandparents.value = value.value.map(el => ({ ...el, // 先筛选出包含已勾选子元素的父元素,再过滤父元素下的子元素 parents: el.parents .filter(parent => parent.children?.some(child => child.checked)) .map(parent => ({ ...parent, children: parent.children?.filter(child => child.checked) || [] })) }))
代码说明
- 外层map:遍历每个祖父级元素,通过解构原对象避免修改原始数据。
- parents数组处理:
- 第一步
filter:保留至少有一个checked: true子元素的父元素,和你原有逻辑一致。 - 第二步
map:对每个符合条件的父元素,再次解构并过滤其children数组,只保留checked: true的子项;用|| []处理children为undefined的边界情况。
- 第一步
运行这段代码后,就能得到你想要的结果:既去掉了无勾选子元素的父元素,也清理了父元素下未勾选的子元素。
内容的提问来源于stack exchange,提问作者Lynx
相关产品推荐
相关产品推荐

