Eka hersada
Eka hersada

Reputation: 15

Convert an Array to Tree in Typescript

I have structure database in array of objects stored like this:

 arry = [{"name": "a", "id": "2", "data":"foo", "parent": "1"},
 {"name": "b", "id": "3", "data":"foo", "parent": "2"},
 {"name": "c", "id": "4", "data":"foo", "parent": "3"},
 {"name": "d", "id": "5", "data":"foo", "parent": "3"},
 {"name": "e", "id": "6", "data":"foo", "parent": "4"},
 {"name": "f", "id": "7", "data":"foo", "parent": "5"}]

I want nested structure like this

{
"2":{
   "name": "a",
   "data": "foo",
  "3":{
     "name": "b",
     "data":"foo",
     "4":{
        "name": "c",
        "data":"foo",
        "6":{
           "name": "e",
           "data": "foo",
          };
       },
      "5":{
         "name": "d",
         "data": "foo",
         "7":{
            "name": "f",
            "data": "foo"
           }
        }
      }
    }
  };

so I can use it Angular Material tree.

Upvotes: 1

Views: 6469

Answers (1)

Kaiido
Kaiido

Reputation: 137131

To do this, you can reduce your array of nodes to a dictionary, using each node's id as index.

This way, you'll have all the nodes accessible by their id directly on the dictionary. You'll thus be able to store each node in its parent easily.

Once all the nodes are stored in their respective parent, you just have to grab the root node from the dictionary, it will hold all your tree.

It may happen that the parent isn't yet in the dictionary when you parse the child, in this case, you can use a dummy object that will play a placeholder the time we come to parse the actual parent node.

var arry = [
 {"name": "a", "id": "2", "data":"foo", "parent": "1"},
 {"name": "b", "id": "3", "data":"foo", "parent": "2"},
 {"name": "c", "id": "4", "data":"foo", "parent": "3"},
 {"name": "d", "id": "5", "data":"foo", "parent": "3"},
 {"name": "e", "id": "6", "data":"foo", "parent": "4"},
 {"name": "f", "id": "7", "data":"foo", "parent": "5"}
];

function totree(branches, node) {
  // if we don't have the parent yet
  if (!branches[node.parent]) {
    // create a dummy placeholder for now
    branches[node.parent] = {};
  }
  // store our node in its parent
  branches[node.parent][node.id] = node;
  // store our node in the full list
  // copy all added branches on possible placeholder
  branches[node.id] = Object.assign(node, branches[node.id]);

  return branches;
}

var tree = arry.reduce(totree, {})['1']; // get only the root node ('1')

console.log(tree);

Upvotes: 5

Related Questions