关键词匹配,过滤树

仅匹配树的最后一级

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())
相关推荐
最贪吃的虎6 分钟前
什么是开源?小白如何快速学会开源协作流程并参与项目
java·前端·后端·开源
裴嘉靖7 分钟前
Vue + ECharts 实现图表导出为图片功能详解
前端·vue.js·echarts
用泥种荷花8 分钟前
【LangChain学习笔记】输出解析器
前端
闲云一鹤36 分钟前
Cesium 使用 Turf 实现坐标点移动(偏移)
前端·gis·cesium
Thomas游戏开发42 分钟前
Unity3D IL2CPP如何调用Burst
前端·后端·架构
想学后端的前端工程师1 小时前
【微前端架构实战指南:从原理到落地】
前端·架构·状态模式
Keya1 小时前
DevEco Studio 使用技巧全面解析
前端·前端框架·harmonyos
_Rookie._1 小时前
web请求 错误拦截
前端
青鸟北大也是北大1 小时前
CSS单位与字体样式全解析
前端·css·html