数据:
let dataArr = [
{
"id": 1,
"children": [
{
"id": 2,
"children":[
{
"id": 3
}
]
}
]
},
{
"id": 4,
"children": [
{
"id": 5,
"children":[
{
"id": 6
}
]
}
]
},
{
"id": 7,
"children": [
{
"id": 8,
"children":[
{
"id": 9
}
]
}
]
},
]
查找方法:
const findParent = (childrenId, arr, path) => {
if (path === undefined) {
path = []
}
for (let i = 0; i < arr.length; i++) {
let tmpPath = path.concat();
tmpPath.push(arr[i].id);
if (childrenId == arr[i].id) {
return tmpPath
}
if (arr[i].children) {
let findResult = findParent(childrenId, arr[i].children, tmpPath);
if (findResult) {
return findResult
}
}
}
}
示例:
let Ids=findParent(3,dataArr)
console.log(Ids,"1111")
//[1,2,3]