方式一:父节点含有搜索内容,则需向下继续搜索,返回含有搜索内容的子节点
fuzzySearchTree = (tree, searchValue) => {
const resTree = [];
(tree || []).forEach(node => {
if (node.name.indexOf(searchValue) > -1) { // 父节点 包含搜索字符串
let arr = [];
if (node.children && node.children.length > 0) {
arr = this.fuzzySearchTree(node.children, searchValue); // 再递归查询子节点是否含有搜索字符串
}
resTree.push({...node, children: arr});
} else { // 父节点 不包含搜索字符串;则还需向下检查子节点是否含有搜索字符串;
if (node.children && node.children.length > 0) {
const arr = this.fuzzySearchTree(node.children, searchValue);
if (arr && arr.length > 0) {
resTree.push({...node, children: arr});
}
}
}
});
return resTree;
}
方式二:父节点含有搜索内容,无需向下继续搜索,直接返回改节点及下面所有子节点
fuzzySearchTree = (tree, searchValue) => {
const resTree = [];
(tree || []).forEach(node => {
if (node.name.indexOf(searchValue) > -1) { // 父节点 包含搜索字符串,直接将父节点及以下的子节点都返回
resTree.push({...node});
} else { // 父节点 不包含搜索字符串;则还需向下检查子节点是否含有搜索字符串;
if (node.children && node.children.length > 0) {
const arr = this.fuzzySearchTree(node.children, searchValue);
if (arr && arr.length > 0) {
resTree.push({...node, children: arr});
}
}
}
});
return resTree;
}
本文介绍了两种FuzzySearchTree的方法,一种是当父节点含有搜索内容时,会递归查询子节点;另一种则是直接返回父节点及其所有子节点,无需进一步搜索。这两种策略适用于处理含有模糊匹配需求的数据结构查询。
840

被折叠的 条评论
为什么被折叠?



