关键词匹配,过滤树

97 阅读1分钟

仅匹配树的最后一级

// 搜索关键字,把对应的枝干从树里过滤出来
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
}

树的每一级都匹配

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
}

匹配文字有两种方式

  • 方式一:靠正则(不推荐)
 const keyReg = new RegExp(keyWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
 keyReg.test(node.name)
  • 方式二:(推荐)
name.toLowerCase().includes(keyWord.toLowerCase())