邻接表中的树结构

问题描述 投票:13回答:2

我正在尝试从具有父ID的平面数组生成层次树对象。

// `parent` represents an ID and not the nesting level.
var flat = [
    { id: 1, name: "Business", parent: 0 },
    { id: 2, name: "Management", parent: 1 },
    { id: 3, name: "Leadership", parent: 2 },
    { id: 4, name: "Finance", parent: 1 },
    { id: 5, name: "Fiction", parent: 0 },
    { id: 6, name: "Accounting", parent: 1 },
    { id: 7, name: "Project Management", parent: 2  }
];

最终的树对象应如下所示:

{ 
    id: 1, 
    name: "Business", 
    children: [
        { 
            id: 2, 
            name: "Management", 
            children: [
                { id: 3, name: "Leadership" },
                { id: 7, name: "Project Management" }
            ]
        }
        // [...]
    ]
}
// [...]

您可以看到我目前在this fiddle上的工作,但仅在前两个级别上有效。

我曾考虑过收集孤儿(来自flat的对象,但tree中没有父母),然后再次遍历它们,以查看它们现在是否有父母。但这可能意味着在树对象上有许多循环,尤其是在多个级别上有许多类别。

我确定有一个更优雅的解决方案。

我正在尝试从具有父ID的平面数组中生成分层树对象。 //`parent`代表一个ID,而不是嵌套级别。 var flat = [{id:1,名称:“ Business”,父级:0},...

javascript tree adjacency-list
2个回答
10
投票

无论树的深度如何,您都可以通过2次传递来完成此操作:


3
投票

更新2,(六年后)

© www.soinside.com 2019 - 2024. All rights reserved.