1

I work with a weird javascript array structured like this: ["node1", "alias1", 1, "node2", "alias2", 2, "node3", "alias3", 2, "node4", "alias4", 1, "node5", "alias5", 2]

This array represent a structured tree(seem to represent...), there is a triplet of information on each node: the node name, the alias and the hierarchy level. To structure this array into a interesting object I need to put all children under their parent, the parent is the one that have "1" in the hierarchy level and the children have "2" in hierarchy level.

So I want to transform this array into this object :

[
   {
      "node_name":"node1",
      "alias":"alias1",
      "children":[
         {
            "node_name":"node2",
            "alias":"alias2"
         },
         {
            "node_name":"node3",
            "alias":"alias3"
         }
      ]
   },
   {
      "node_name":"node4",
      "alias":"alias4",
      "children":[
         {
            "node_name":"node5",
            "alias":"alias5"
         }
      ]
   }
]

I could make it with hands a construct somethings big and unoptimal, but before I try anything I want to know if there is something more simple, something that already exist that could help me to do this transformation.

PS:

  1. I can't use non-native javascript, so I can't use external library, I have to solve this problem on my browser console.

  2. I could try to help myself with this topic but in this case there is a link between parent and children by parentId, but in my case there no parentId neither in parent object nor in children object

bosskay972
  • 890
  • 1
  • 6
  • 27

1 Answers1

2

You could take an array for keeping the last inserted node for the level.

const
    data = ['node1', 'alias1', 1, 'node2', 'alias2', 2, 'node3', 'alias3', 2, 'node4', 'alias4', 1, 'node5', 'alias5', 2],
    result = [],
    levels = [{ children: result }];

for (let i = 0; i < data.length; i += 3) {
    const
        node_name = data[i],
        alias = data[i + 1],
        level = data[i + 2] - 1;
        
    (levels[level].children ??= []).push(levels[level + 1] = { node_name, alias });
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392