Converting flat structure to hierarchical

前端 未结 6 1414
感情败类
感情败类 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:09

    I tried to write the algorithm in pseudocode, ended up with JS code that almost works (perhaps some additional validations/checks are needed) but shows the general approach to the problem.

    //Lets separate children (nodes with a parent) from roots (nodes without a parent)
    var children = flatArray.filter(function(object){
        return object.parent !== null;
    });
    
    var roots = flatArray.filter(function(object){
        return object.parent === null;
    });
    
    //And add each child to the nodes tree
    children.foreach(function(child){
        recursiveAdd(roots, child);
    });
    
    //To add a children node, node tree is searched recursively for a parent
    function recursiveAdd(nodes, child){
        nodes.foreach(function(parent){
            if(parent.guid === child.parent){
                parent.Children = parent.Children | [];
                parent.Children.add(child);
            } else if(parent.Children) {
                recursiveAdd(parent.Children, child);
            }
        });
    }
    
    //Temporary children array can be garbage collected
    children = null;
    //Resulting node tree
    var recursiveArray = roots;
    

提交回复
热议问题