You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 16:33:28