JavaScript:在嵌套树形结构中实现保留层级关系的name字段包含式搜索
实现树形结构的包含式搜索并保留父子层级
我来帮你搞定这个树形搜索的问题!你之前的代码只能做精确匹配,而且没有递归遍历子节点,也没处理匹配节点的层级保留需求,下面是完整的解决方案:
核心思路
要满足你的需求,我们需要做到这几点:
- 递归遍历整个树形结构的每个节点
- 对每个节点的
name字段做包含式匹配(而非精确相等) - 保留匹配节点的完整父子层级:如果某个子节点匹配,它的所有父节点也需要被保留,只过滤掉完全不相关的分支
完整代码实现
const arr = [ { name: "internalcorp.com", config: { val1: false, val2: false }, children: [ { name: "internalcorp.com.child1", config: { val1: true, val2: true }, children: [ { name: "internalcorp.com.grandchild1", config: { val1: true, val2: true }, children: [] }, { name: "internalcorp.com.grandchild2", config: { val1: false, val2: true }, children: [] } ] }, { name: "internalcorp.com.child2", config: { val1: true, val2: false }, children: [] } ] }, { name: "internalcorpwebsite.com", children: [ { name: "internalcorpwebsite.com.child1", className: "level-1 leaf", children: [], val1: false, val2: false } ], config: { val1: false, val2: false } } ]; function searchTree(tree, keyword) { // 用reduce遍历节点,收集符合条件的结果 return tree.reduce((resultList, currentNode) => { // 检查当前节点name是否包含搜索关键词 const isCurrentMatch = currentNode.name.includes(keyword); // 递归处理子节点,得到子树中匹配的分支 const matchedChildren = searchTree(currentNode.children || [], keyword); // 如果当前节点匹配,或者有匹配的子节点,就保留这个节点 if (isCurrentMatch || matchedChildren.length > 0) { // 复制原节点,避免修改原树形结构 const nodeToKeep = { ...currentNode }; // 更新children为匹配的子分支(没有匹配子节点则设为空数组) nodeToKeep.children = matchedChildren.length > 0 ? matchedChildren : []; resultList.push(nodeToKeep); } return resultList; }, []); } // 测试示例:搜索包含"website"的节点 console.log(searchTree(arr, "website")); // 测试示例:搜索包含"grandchild1"的节点 console.log(searchTree(arr, "grandchild1"));
代码说明
- 包含式匹配:用
String.includes()代替精确相等判断,实现模糊搜索 - 递归遍历:对每个节点的
children递归调用searchTree,确保遍历所有层级 - 层级保留:只有当节点自身匹配,或者子节点中有匹配项时,才将该节点加入结果,同时保留其匹配的子分支,这样就完整保留了从根到匹配节点的层级关系
- 不修改原数据:通过对象展开
{ ...currentNode }复制节点,避免破坏原树形结构
扩展优化
如果需要不区分大小写的搜索,可以把匹配判断改成:
const isCurrentMatch = currentNode.name.toLowerCase().includes(keyword.toLowerCase());
内容的提问来源于stack exchange,提问作者user16860065
相关产品推荐
相关产品推荐

