Skip to content Skip to sidebar Skip to footer

How To Convert Nested Set Into Nested Array In Javascript?

There is following data. [ {'no':1, 'name':'ELECTRONICS', 'depth':0}, {'no':2, 'name':'TELEVISIONS', 'depth':1}, {'no':3, 'name':'TUBE', 'depth':2}, {'no':4, 'name'

Solution 1:

You could use a helper array for the levels.

var array = [{ no: 1, name: "ELECTRONICS", depth: 0 }, { no: 2, name: "TELEVISIONS", depth: 1 }, { no: 3, name: "TUBE", depth: 2 }, { no: 4, name: "LCD", depth: 2 }, { no: 5, name: "PLASMA", depth: 2 }, { no: 6, name: "PORTABLE ELECTRONICS", depth: 1 }, { no: 7, name: "MP3 PLAYERS", depth: 2 }, { no: 8, name: "FLASH", depth: 3 }, { no: 9, name: "CD PLAYERS", depth: 2 }, { no: 10, name: "2 WAY RADIOS", depth: 2 }],
    result = [],
    levels = [{ children: result }];

array.forEach(function (o) {
    levels[o.depth].children = levels[o.depth].children || [];
    levels[o.depth].children.push(levels[o.depth + 1] = o);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Solution 2:

//The trees root = our expected result  
 const result = [];
 var acc  = { depth: -1, children: result};

 for(const el of data){
   //walk upwards in the tree
   var up = acc.depth - el.depth + 1 ;
   while(up--){ acc = acc.parent }
   //walk down and add the current el as a child
   el.parent = acc;
   (acc.children || (acc.children = [])).push(el);
   acc = el;
}

console.log(result);

You may just walk through a tree (acc) and link parents/children together.


Post a Comment for "How To Convert Nested Set Into Nested Array In Javascript?"