Converting flat structure to hierarchical

前端 未结 6 1420
感情败类
感情败类 2020-12-05 12:02

I need to create function which will be able to convert flat object to recursive object. Here is my example: I have flat array:

var flatArray = [
    {
              


        
6条回答
  •  醉酒成梦
    2020-12-05 12:12

    This one works nicely and is easy to read:

    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
    }
    

提交回复
热议问题