karlitos
karlitos

Reputation: 1656

Construct hierarchy tree from flat list with children field and preserve the children order?

Similar question was asked previously here and here, there are npm-packages as well BUT - I am not able to find a JavaScript code snippet or npm package which would allow preserving the the order of the children

Consider following data structure:

var nodes = [{id: 'a', parent: null, children: ['c', 'b']},
             {id: 'b', parent: 'a', children: []},
             {id: 'c', parent: 'a', children: []}]

I would like to get a nested object like this:

var tree = {id: 'a', parent: null, children: [
    {id: 'c', parent: 'a', children: []},
    {id: 'b', parent: 'a', children: []}
]}

The important fact is, that since the order of the children of a is c, b, the resulting children array in the nested structure will preserve the order.

Upvotes: 1

Views: 392

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138235

Quite simple if you build up a Map first:

 const nodeById = new Map(nodes.map(el => [el.id, el]));

Then you can easily build up the tree:

 let root;

 for(const node of nodes) {
   node.children = node.children.map(id => nodeById.get(id));
   if(!node.parent) root = node;
 }

Upvotes: 2

Related Questions