javascript - 如何在 typescript 中找到树中的树

标签 javascript arrays typescript recursion ecmascript-6

假设我在 javascript 中有一棵树

a1 
--b
----c1
a2
--b2
--b3
----c2

如果我想找到c2,它应该返回a2->b3->c2

假设我的 json 看起来像这样?

treeFamily = {
            name : "Parent",
            children: [{
                name : "Child1",
                children: [{
                    name : "Grandchild1",
                    children: []
                },{
                    name : "Grandchild2",
                    children: []
                },{
                    name : "Grandchild3",
                    children: []
                }]
            }, {
                name: "Child2",
                children: []
            }]
        };

最佳答案

您可以检查嵌套的子级是否具有所需的键/值。然后获取name并将结果交给外部调用。

function findPath(array, target) {
    var path;
    array.some(({ name, children }) => {
        var temp;
        if (name === target) {
            path = [name];
            return true;
        }
        if (temp = findPath(children, target)) {
            path = [name, ...temp];
            return true;
        }
    });
    return path;
}

var treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] };

console.log(findPath([treeFamily], 'Grandchild2'));
console.log(findPath([treeFamily], 'foo'));

关于javascript - 如何在 typescript 中找到树中的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53175946/

相关文章:

c - 如果用户输入 "*"则添加 1,或者如果用户输入 ""到 C 数组中则添加 0

c# - Unity C# 将float转换为字节数组并用node js读取

javascript - 根据 React 页面中的行数据更改 scss 中的颜色

php - Perl 中的动态下拉列表

c - Xcode 给出了简单 C 数组的错误总和

javascript - Angular 2显示/隐藏路由器导出并重定向到html页面

typescript - Vue 增强类型 - XYZ 在类型上不存在

typescript - VS Code 中 Vuex 商店的 Intellisense

javascript - 我可以在 Vue.Js 的计算属性中传递参数吗

javascript - 从 dataurl 获取图像的高度和宽度