关键词匹配,过滤树

仅匹配树的最后一级

js 复制代码
// 搜索关键字,把对应的枝干从树里过滤出来
export function rebuildTree(keyWord, arr) {
  if (!arr) {
    return []
  }
  let newarr = []
  arr.forEach((node) => {
    const keyReg = new RegExp(keyWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
    const matchedChildren = rebuildTree(keyWord, node.child)
    if (keyReg.test(node.name)) {
      // 最后一层节点 匹配到关键字,push进去
      if (matchedChildren.length === 0 && node.child.length === 0) {
        const obj = {
          ...node,
          child: matchedChildren,
        };
        newarr.push(obj);
      }
    }
    // 后代有匹配到的,该树留着
    if (matchedChildren.length > 0) {
      const obj = {
        ...node,
        child: matchedChildren,
      };
      newarr.push(obj);
    }
  })
  return newarr
}

树的每一级都匹配

js 复制代码
export function rebuildTree(keyWord, arr) {
  if (!Array.isArray(arr)) {
    return []
  }
  if (!keyWord) return arr
  let result = []
  arr.forEach((node) => {
    const matchedChildren = node.child ? rebuildTree(keyWord, node.child) : [];
    if (node.name.toLowerCase().includes(keyWord.toLowerCase())) {
      result.push({ ...node });
    } else if (matchedChildren.length > 0) {
      // 如果子节点中有匹配的,保留当前节点,并替换 child 为过滤后的子树
      result.push({
        ...node,
        child: matchedChildren
      });
    }
  })
  return result
}

匹配文字有两种方式

  • 方式一:靠正则(不推荐)
js 复制代码
 const keyReg = new RegExp(keyWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
 keyReg.test(node.name)
  • 方式二:(推荐)
js 复制代码
name.toLowerCase().includes(keyWord.toLowerCase())
相关推荐
Csvn5 小时前
OpenSpec 详细使用教程
前端
之歆6 小时前
Day19_LESS 完全指南——从入门到工程实践
前端·css·less
云水一下7 小时前
HTML5 从入门到精通:实战收官——从零搭建完整静态网站,综合运用所有知识
前端·html5
不总是7 小时前
Windows 系统 Node.js 免安装版(zip)安装与配置教程(2026 最新)
前端·windows·node.js
冬奇Lab7 小时前
每日一个开源项目(第105篇):Twenty - 跳出 Salesforce 的圈套,定义现代开源 CRM
前端·后端·开源
zhangyao9403308 小时前
开发pc端时,表格的高度怎么设置才能铺满页面
前端·javascript·elementui
kjs--8 小时前
浏览器书签执行脚本
前端
之歆9 小时前
Day16_JavaScript 轮播图与事件工程实战(下篇)
服务器·开发语言·前端·javascript·网络·性能优化
沄媪9 小时前
CSRF 跨站请求伪造
前端·ctf·csrf
kyriewen9 小时前
我关掉了Copilot:因为我写的代码出现在了别人的建议里
前端·javascript·ai编程