SOURCE

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);
}
console.time("sort");
let targetName = "third-menu";
let parents = findParentsTailRecursive(arr, targetName);

if (parents) {
    console.log("归属的父级信息(从树的顶层到当前层级):", parents);
} else {
    console.log("未找到归属的父级信息。");
}
console.timeEnd("sort");
console 命令行工具 X clear

                    
>
console