递归获取
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;
}
let targetName = "third-menu";
let parents = findParents(arr, targetName);
if (parents) {
console.log("归属的父级信息(从树的顶层到当前层级):", parents.reverse());
} else {
console.log("未找到归属的父级信息。");
}
尾递归获取
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 findParentsTailRecursive(tree, targetName, parents = [], index = 0) {
if (index >= tree.length) {
return null;
}
const currentNode = tree[index];
const updatedParents = parents.concat(currentNode);
if (currentNode.name === targetName) {
return updatedParents;
}
if (currentNode.children) {
const result = findParentsTailRecursive(currentNode.children, targetName, updatedParents);
if (result) {
return result;
}
}
return findParentsTailRecursive(tree, targetName, parents, index + 1);
}
let targetName = "third-menu";
let parents = findParentsTailRecursive(arr, targetName);
if (parents) {
console.log("归属的父级信息(从树的顶层到当前层级):", parents);
} else {
console.log("未找到归属的父级信息。");
}