JS如何判断数组对象包含指定值并返回匹配的对象数组
实现嵌套数组对象的指定值筛选功能
核心需求
从给定的菜单结构数组中,筛选出children子数组内包含指定name值的父级对象,最终返回由符合条件的父级对象组成的新数组。以示例数据为例,传入目标值"bad"时,仅保留title为"two"的父对象。
基础实现(适配示例的两层结构)
两层结构直接用数组原生的filter+some组合实现即可,逻辑简单易读,性能也足够:
filter负责遍历外层数组,保留返回值为true的数组项some负责检查当前父项的children中是否存在匹配值,只要找到1个匹配项就会终止遍历返回true,不需要跑完整个子数组
const menu = [ { title: "one", children: [{name: "hello"}, {name: "bye"}], },{ title: "two", children: [{name: "good"}, {name: "bad"}], }, ] function filterTargetMenu(menuList, targetVal) { return menuList.filter(parent => { return parent.children.some(child => child.name === targetVal) }) } // 调用测试 const res = filterTargetMenu(menu, "bad") console.log(res) /* 输出和预期完全一致: [ { title: "two", children: [{name: "good"}, {name: "bad"}], } ] */
扩展:多层嵌套结构的递归实现
如果后续菜单层级变深(比如children下还有多层子children),可以用递归做深度查找,不需要手动写多层判断:
function deepFilterMenu(menuList, targetVal) { return menuList.filter(item => { // 检查当前节点的直接子项是否匹配 const directMatch = item.children?.some(child => child.name === targetVal) if (directMatch) return true // 递归检查更深层级的子项 if (Array.isArray(item.children) && item.children.length) { return deepFilterMenu(item.children, targetVal).length > 0 } return false }) }
内容的提问来源于stack exchange,提问作者god_z
相关产品推荐
相关产品推荐

