var nodes = [
{
"id": 1,
"children": [
{
"id": 3,
"children": [
{"id": 4},
{"id": 9}
]
},
{
"id": 10
},
]
},
{
"id": 2
},
{
"id": 6,
"children" : [
{ "id": 5},
{ "id": 7},
{ "id": 8}
]
}
];
//
function findPathById(arr, id, key, resultTemp = []) {
for (let index = 0; index < arr.length; index++) {
const element = arr[index];
let result = resultTemp.slice() // 浅拷贝一下
result.push(element[key])
if (element[key] === id) {
return result
}
if (element.children) {
const findResult = findPathById(element.children, id, key, result)
if (findResult) {
return findResult
}
}
}
}
console.log(findPathById(nodes, 9, 'id')) // [1,3,9]
网友评论