let data = [
{
"id": 1,
"label": "菜单1",
"children": [
{
"id": 2,
"label": "菜单1-1",
"children": [
{
"id": 3,
"label": "菜单1-1-1",
},
{
"id": 4,
"label": "菜单1-1-2",
}
],
},
{
"id": 5,
"label": "菜单1-2",
"children": [
{
"id": 6, //根据这个id,查找它的所有上级
"label": "菜单1-2-1",
},
{
"id": 7,
"label": "菜单1-2-2",
},
],
},
]
},
{
"id": 11,
"label": "菜单2",
"children": [
{
"id": 8,
"label": "菜单2-1",
"children": [
{
"id": 9,
"label": "菜单2-1-1",
},
{
"id": 10,
"label": "菜单2-1-2",
}
],
},
]
}
]
//data:要遍历的数据, target:查找目标, result用于装查找结果的数组
function findParent(data, target, result) {
for (let item of data) {
console.log(2222)
if (item.id === target.id) {
//将查找到的目标数据加入结果数组中
//可根据需求unshift(item.id)或unshift(item)
result.unshift(item.label)
return true
}
if (item.children && item.children.length > 0) {
//根据查找到的结果往上找父级节点
let isFind = findParent(item.children, target, result)
console.log(11111)
if (isFind) {//符合条件的push父节点
result.unshift(item.label)
return true
}
}
}
//走到这说明没找到目标
return false
}
let target = { "id": 6, "label": "菜单1-2-1" }
let result = []
findParent(data, target, result)
console.log(result) // ['菜单1', '菜单1-2', '菜单1-2-1']
console