有如下需求:
一个树形结构:
const data = [
{
"id": 1,
"name": "test0",
"children": [
{
"id": 3,
"name": "test01",
"parent": {
"id": 1,
"name": "test0"
},
"children": [
{
"id": 8,
"name": "test011",
"children": [],
"parent": {
"id": 3,
"name": "test01"
}
},
{
"id": 9,
"name": "test012",
"children": [],
"parent": {
"id": 3,
"name": "test01"
}
},
{
"id": 10,
"name": "test013",
"node_order": 2,
"children": [],
"parent": {
"id": 3,
"name": "test01"
}
}
]
},
{
"id": 6,
"name": "test02",
"children": [
{
"id": 14,
"name": "test021"
},
{
"id": 15,
"name": "test022"
}
]
}
]
},
{
"id": 2,
"name": "test1",
"children": [
{
"id": 5,
"name": "test11",
"children": [
{
"id": 11,
"name": "test111"
},
{
"id": 12,
"name": "test112"
},
{
"id": 13,
"name": "test113",
"node_order": 2
}
]
},
{
"id": 7,
"name": "test12",
"children": [
{
"id": 16,
"name": "test121"
},
{
"id": 17,
"name": "test122"
}
]
}
]
}
]
需要从中遍历出id值为[ 3,6 ]的数据。
// 获取所有父级
function getTreeParents(tree=[], ids=[]) {
const currentMenu = ids.map(m => {
var stark = [];
stark = stark.concat(tree);
while(stark.length) {
var temp = stark.shift();
if(temp.children) {
stark = stark.concat(temp.children);
}
if(temp.id === m) {
return temp;
}
}