仅匹配树的最后一级
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())