javascript数组树搜索保留节点和父节点
尝试实现一个树搜索函数,该函数接受一个数组(树结构)和一个字符串关键字,将返回一个树数组,但只保留匹配的节点及其父节点javascript数组树搜索保留节点和父节点,javascript,search,tree,treeview,Javascript,Search,Tree,Treeview,尝试实现一个树搜索函数,该函数接受一个数组(树结构)和一个字符串关键字,将返回一个树数组,但只保留匹配的节点及其父节点 function search(nodes, keyword){ } const nodes = [ { value: "1-1", children: [ { value: "1-1-1"}, { value: "1-1-2", children:[ { value: "1-1-2-1",
function search(nodes, keyword){
}
const nodes = [
{
value: "1-1",
children: [
{ value: "1-1-1"},
{ value: "1-1-2", children:[
{
value: "1-1-2-1",
children: [
{ value: "1-1-2-1-1" },
{ value: "1-1-2-1-2" }
]
},
{
value: "1-1-2-2"
}
] }
]
},
{
value: "1-2",
children: [
{ value: "1-2-1"},
{ value: "1-2-2", children:[
{
value: "1-2-2-1",
children: [
{ value: "1-2-2-1-1" },
{ value: "1-2-2-1-2" }
]
},
{
value: "1-2-2-2"
}
] }
]
},
];
预期输出将是一棵树,其中节点的值包含“1-1-2-1”及其父节点,如下所示
const searchedNodes = search(nodes, "1-1-2-1");
[
{
value: "1-1",
children: [
{ value: "1-1-2", children:[
{
value: "1-1-2-1",
children: [
{ value: "1-1-2-1-1" }
]
}
] }
]
}
]
*/
2018-06-26更新
我做了一个有效的(DFS),但可能不是很有效
const search = (nodes, keyword) => {
let newNodes = [];
for (let n of nodes) {
if (n.children) {
const nextNodes = this.keywordFilter(n.children, keyword);
if (nextNodes.length > 0) {
n.children = nextNodes;
} else if (n.label.toLowerCase().includes(keyword.toLowerCase())) {
n.children = nextNodes.length > 0 ? nextNodes : [];
}
if (
nextNodes.length > 0 ||
n.label.toLowerCase().includes(keyword.toLowerCase())
) {
newNodes.push(n);
}
} else {
if (n.label.toLowerCase().includes(keyword.toLowerCase())) {
newNodes.push(n);
}
}
}
return newNodes;
};
您需要迭代相同级别的节点并检查值是否相等,然后获取该节点并退出循环。否则,请检查子对象并生成新对象,以防止原始数据发生变异
函数搜索(节点、值){
var结果;
nodes.some(o=>{
儿童;
如果(o.value==值){
返回结果=o;
}
if(o.children&(children=search(o.children,value))){
返回结果=Object.assign({},o,{children});
}
});
返回结果;
}
const nodes=[{value:“1-1”,children:[{value:“1-1-1”},{value:“1-1-2-1”,children:[{value:“1-1-2-1-1”},{value:“1-1-2-1-2”},{value:“1-1-2-2”},{value:{value:“1-2-1”},{value:{“1-2-2-1-2”}],{value:“1-2-2-2”}]}];
console.log(搜索(节点,“1-1-2-1”);
。作为控制台包装{max height:100%!important;top:0;}
什么符合'1-1-2-1-1'
而不是'1-1-2-1-2'
?顺便问一下,你试过什么?