JavaScript:在树递归中查找元素的所有父项 [英] JavaScript: Find all parents for element in tree recursive
本文介绍了JavaScript:在树递归中查找元素的所有父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一棵像这样的树
var datas = {
'tree': [
{
'name': 'name1',
'tree': [
{'name': 'name2'},
{'name': 'name3'},
{
'name': 'name4',
'tree': [
{'name': 'name5'},
{'name': 'name6'}
]
},
{'name': 'name7'}
]
},
{
'name': 'name8',
'tree': [
{'name': 'name9'}
]
}
]
}
我想找到特定 id 的所有父项
I want to find all the parents of the specifig id
例如在树演示中,如果我寻找'name5',我想找到name1,name4,name5"
for example in the tree demo, if I look for 'name5' I want to find "name1,name4,name5"
我写了这段代码,但结果是错误的,我得到了其他元素的 id,而不仅仅是父元素的 id
I wrote this code but the results wrong and I got the ids of other elements and not the parents only
这是我的代码
keys: string[];
pathFound: boolean = false;
getLevel(event: iEventBase, id: string, path: string[]): void {
if (this.pathFound) return;
event.content.forEach((key) => {
if (key.id == id) {
if(!path){
path = [];;
}
path.push(key.id);
this.keys = path;
this.pathFound = true;
return;
}
if (key.type === "page") {
if(!path){
path = [];
}
path.push(key.id);
this.getLevel(key, id, path);
}
})
}
}
this.getLevel(state.mainEvent.content.page, event.id, null);
推荐答案
您可以使用递归方法,通过检查名称并返回一个只有节点的新数据结构到所需对象.
You could use a recursive approach by checking the name and return a new data structure with only the nodes to the wanted object.
function find({ tree = [], ...object }, name) {
var result;
if (object.name === name) return object;
return tree.some(o => result = find(o, name)) && Object.assign({}, object, { tree: [result] });
}
var datas = { tree: [{ name: 'name1', tree: [{ name: 'name2' }, { name: 'name3' }, { name: 'name4', tree: [{ name: 'name5' }, { name: 'name6' }] }, { name: 'name7' }] }, { name: 'name8', tree: [{ name: 'name9' }] }] };
console.log(find(datas, 'name5'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于JavaScript:在树递归中查找元素的所有父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文