Converting flat structure to hierarchical

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

    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",
        },      
    ];
    
    //for printing
    function htmlPrint(obj) {
      document.write('
    '+JSON.stringify(obj,null,2)+'
    '); }; var guids = {}; var roots = []; flatArray.forEach(function(node){ guids[node.guid] = node; //save into a hash node.Children = []; //make sure it has a children array //save it as root if it is a root if(node.parent === null){ roots.push(node);} }); flatArray.forEach(function(node){ //if it has a parent, add self to parent's children var parent = guids[node.parent]; if(parent) parent.Children.push(node); }); htmlPrint(roots);

提交回复
热议问题