将平面结构转换为分层结构

Ada*_*zek 10 javascript algorithm

我需要创建能够将平面对象转换为递归对象的函数.这是我的例子:我有平面阵列:

var flatArray = [
    {
        Description: "G",
        guid: "c8e63b35",
        parent: null,
    },
    {
        Description: "Z",
        guid: "b1113b35",
        parent: "c8e63b35",
    },
    {
        Description: "F",
        guid: "d2cc2233",
        parent: "b1113b35",
    },
    {
        Description: "L",
        guid: "a24a3b1a",
        parent: null,
    },
    {
        Description: "K",
        guid: "cd3b11caa",
        parent: "a24a3b1a",
    },      
]
Run Code Online (Sandbox Code Playgroud)

结果应该是:

recursiveArray = [
    {
        Description: "G",
        guid: "c8e63b35",
        parent: null,
        Children: [
            {
                Description: "Z",
                guid: "b1113b35",
                parent: "c8e63b35",
                Children: [
                    {
                        Description: "F",
                        guid: "d2cc2233",
                        parent: "b1113b35",
                    }
                ]
            }, 
        ]
    },
    {
        Description: "L",
        guid: "a24a3b1a",
        parent: null,
        Children: [
        {
            Description: "K",
            guid: "cd3b11caa",
            parent: "a24a3b1a",
        }
    }
]
Run Code Online (Sandbox Code Playgroud)

请帮我找到办法.一个工作的算法将不胜感激,因为我有理解如何正确执行此操作的问题.在每种情况下,我都需要在递归结构中找到已检查元素的特定位置,并将其推送到finded element children数组中.我认为这是愚蠢和低效的.有没有办法快速有效地做到这一点?

编辑:递归数组格式错误.现在应该没问题.我的数组没有任何排序.

fra*_*cod 17

这个很好用,很容易阅读:

function flatToHierarchy (flat) {

    var roots = [] // things without parent

    // make them accessible by guid on this map
    var all = {}

    flat.forEach(function(item) {
      all[item.guid] = item
    })

    // connect childrens to its parent, and split roots apart
    Object.keys(all).forEach(function (guid) {
        var item = all[guid]
        if (item.parent === null) {
            roots.push(item)
        } else if (item.parent in all) {
            var p = all[item.parent]
            if (!('Children' in p)) {
                p.Children = []
            }
            p.Children.push(item)
        }
    })

    // done!
    return roots
}
Run Code Online (Sandbox Code Playgroud)