关键词匹配,过滤树

仅匹配树的最后一级

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())
相关推荐
yb305小白2 小时前
echarts 排名Y轴数据过多出现滚动条,排名柱形条绑定事件
前端·echarts
skywalk81632 小时前
Kotti Next:使用FastAPI+Vue 3构建的现代无头CMS-Kotti CMS的精神继承者(使用WorkBuddy AI自动编程)
前端·vue.js·人工智能·fastapi·kotti
小码哥_常2 小时前
Android开发秘籍:给图片加上独特水印
前端
坊钰2 小时前
SpringBean的生命周期
前端·html
happymaker06262 小时前
vue的基本使用和指令
前端·javascript·vue.js
threerocks2 小时前
【前端转 Agent】01 | 从 Claude Code 开源热议聊起,不急着转 Python
前端·agent·claude
凉生阿新2 小时前
【React】从零配置 Git Hooks:提交前自动校验与格式化(Vite + React 19)
前端·git·react.js
英俊潇洒美少年2 小时前
Vue3 为什么不做 Fiber / 并发渲染?
前端·javascript·vue.js
早已忘记3 小时前
CI相关项
java·前端·ci/cd