let arr = [
{
name: "/",
meta: {},
children: [
{
name: "home",
},
{
name: "home2",
},
{
name: "common-components",
children: [
{
name: "form-component",
}
]
},
{
name: "multilevel-menu",
children: [
{
name: "second-menu",
children: [
{
name: "third-menu",
}
]
}
]
}
]
}
];
// 递归实现
function findParents(tree, targetName, parents = []) {
for (let node of tree) {
if (node.name === targetName) {
return parents.concat(node);
}
if (node.children) {
let found = findParents(node.children, targetName, parents.concat(node));
if (found) {
return found;
}
}
}
return null;
}
console.time("sort");
let targetName = "third-menu";
let parents = findParents(arr, targetName);
if (parents) {
console.log("归属的父级信息(从树的顶层到当前层级):", parents.reverse());
} else {
console.log("未找到归属的父级信息。");
}
console.timeEnd("sort");
console