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

如何实现嵌套对象数组全层级name属性的深度过滤功能

实现方案

固定三层层级实现(适配你当前的明确结构)

你当前的代码只检查了最外层对象的name属性,且没有正确返回布尔结果,无法匹配子层级内容。针对你固定的「主对象→subMenus→innerSubMenus」三层结构,可以直接逐层遍历判断:

function deepFilter(inputText) {
  const keyword = inputText.toLowerCase();
  // 遍历最外层数组
  for (const topItem of data) {
    // 匹配最外层name
    if (topItem.name.toLowerCase().includes(keyword)) {
      return true;
    }
    // 遍历第二层subMenus
    if (topItem.subMenus && topItem.subMenus.length) {
      for (const subItem of topItem.subMenus) {
        if (subItem.name.toLowerCase().includes(keyword)) {
          return true;
        }
        // 遍历第三层innerSubMenus
        if (subItem.innerSubMenus && subItem.innerSubMenus.length) {
          for (const innerItem of subItem.innerSubMenus) {
            if (innerItem.name.toLowerCase().includes(keyword)) {
              return true;
            }
          }
        }
      }
    }
  }
  // 全层级无匹配
  return false;
}

上述代码可直接跑通你给出的所有测试用例,符合预期输出。

通用递归实现(支持任意层级嵌套)

如果后续你的菜单结构可能新增嵌套层级,可以用递归方案实现,无需修改代码即可兼容更多嵌套层级:

// 递归检查单个对象及所有子级数组是否存在匹配name
function checkItemMatch(item, keyword) {
  if (item.name?.toLowerCase().includes(keyword)) {
    return true;
  }
  // 遍历对象所有属性,数组类型的属性递归检查子项
  for (const prop in item) {
    const value = item[prop];
    if (Array.isArray(value)) {
      const hasMatch = value.some(child => checkItemMatch(child, keyword));
      if (hasMatch) return true;
    }
  }
  return false;
}

function deepFilter(inputText) {
  const keyword = inputText.toLowerCase();
  return data.some(topItem => checkItemMatch(topItem, keyword));
}

注:代码中使用的可选链?.为ES2020语法,如果你运行的环境不支持该语法,可以把item.name?.toLowerCase()替换为item.name && item.name.toLowerCase()即可。

内容的提问来源于stack exchange,提问作者Hakim Asa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:06:04