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

ReactJs如何实现嵌套对象过滤 现有方法仅能匹配外层title

React嵌套树对象全层级过滤方案

实现思路

  • 递归遍历所有层级的节点,同时判断当前节点和所有子节点的title是否匹配搜索关键词
  • 父节点只要满足「自身title匹配」或「存在匹配的子节点」两个条件之一就保留,子节点仅保留匹配的项
  • 采用纯函数实现,不会修改原始树数据,符合React不可变数据要求

完整代码

1. 封装递归过滤函数

/**
 * 树结构全层级title过滤
 * @param {Array} tree 原始树数据
 * @param {String} keyword 搜索关键词
 * @returns {Array} 过滤后的树数据
 */
const filterTree = (tree, keyword) => {
  const lowerKeyword = keyword.toLowerCase();
  return tree.reduce((result, node) => {
    // 判断当前节点是否匹配
    const isCurrMatch = node.title.toLowerCase().includes(lowerKeyword);
    // 递归过滤子节点
    const filteredChildren = node.children ? filterTree(node.children, keyword) : [];
    // 满足匹配条件则保留节点
    if (isCurrMatch || filteredChildren.length) {
      result.push({
        ...node,
        // 有匹配子节点时替换为过滤后的子节点列表
        children: filteredChildren.length ? filteredChildren : node.children
      });
    }
    return result;
  }, []);
};

2. 业务中调用

// 从输入事件获取搜索词
const searchKeyword = e.target.value.trim();
// 搜索词为空直接返回原数据,否则走过滤逻辑
const filteredTree = searchKeyword ? filterTree(treeData, searchKeyword) : [...treeData];

效果示例

当搜索关键词为Anu时,返回的过滤结果如下:

[
  {
    title: 'Orange',
    key: '0-0',
    children: [
      {
        title: 'Anu',
        key: '0-0-0',
        isLeaf: true,
      }
    ]
  }
]

自定义调整说明

如果不需要保留仅子节点匹配的父节点,只需要把过滤逻辑中的|| filteredChildren.length条件删除即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:27:01