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

如何通过搜索关键词过滤JavaScript多层嵌套对象数组

嵌套对象数组过滤实现方案

实现思路

  • 采用递归深度遍历数组节点,对每个节点做两项校验:
    • 节点本身的label属性是否包含搜索关键词
    • 节点的children数组递归过滤后是否存在有效留存
  • 只要满足以上任意一个条件,就保留当前节点,同时将递归过滤后的children赋值给当前节点,无匹配的分支会被完全剔除
  • 处理过程中采用浅拷贝节点,不会污染原始数组

实现代码

function filterNestedArray(arr, keyword) {
  // 统一转小写实现不区分大小写搜索,不需要可去掉toLowerCase
  const lowerKeyword = keyword.toLowerCase();
  return arr.reduce((result, node) => {
    // 浅拷贝节点避免修改原数组数据
    const filteredNode = {...node};
    // 先递归处理子节点数组
    if (filteredNode.children?.length) {
      filteredNode.children = filterNestedArray(filteredNode.children, keyword);
    }
    // 判断当前节点是否需要保留
    const isCurrentMatch = filteredNode.label.toLowerCase().includes(lowerKeyword);
    const hasValidChildren = filteredNode.children?.length > 0;
    if (isCurrentMatch || hasValidChildren) {
      result.push(filteredNode);
    }
    return result;
  }, []);
}

调用示例

// 搜索关键词 nodata
const res1 = filterNestedArray(array, 'nodata');
// 搜索关键词 spa
const res2 = filterNestedArray(array, 'spa');

返回结果与你需求的示例完全一致,如果需要扩展匹配其他属性(比如同时匹配value、category等),仅需要调整isCurrentMatch的判断逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 18:12:02