Luca Adrian Luca Adrian - 4 months ago 7
Javascript Question

Javascript create array of unknown dimensional size

Though I am programming Javascript several years and at least thought to know the most of it's features and problems, I came across a new one today.

I have an array of device, each device contains a path property. In this path property is also an array.

[
{ // Device object
path: [1]
name: "Device 1",...
},
{ // Device object
path: [1,3]
name: "Device 13",...
},
{ // Device object
path: [1,3,1]
name: "Device 131",...
}...
]


This path property represents the path in an array, I have to create. So the structure above should result in the following (I know it is not valid JS):

[
1 => {
name: "Device 1",
children: [
3 => {
name: "Device 13",
children: [
1 => {
name: "Device 131",
children: [],...
},
],...
},
],...
},
]


In any other language like e.g. php I would use a reference or a pointer and then looping through the path-array:

$newArr = [];
$ptr = &$newArr;
foreach($path as $key){
$ptr = &$ptr[$key].children;
}


The only way I can think of doing something like this in JS is by using eval. But maybe you got some better ideas.

To clarify what I want: The first structure should be somehow processed and be "converted to the second structure". The third and last code snippet is the approach I would use in PHP.

Thank You

Luca

Answer

lets try this (untested):

var tree = new Object();

for(var key in yourFlatArray){
    var path = yourFlatArray[key].path;
    var node = tree;
    while(path.length){
        if(!(path[0] in node)){
            node[path[0]] = new Object();
            node[path[0]]['children'] = new Array();
            node[path[0]]['name'] = yourFlatArray[key].name;
        }
        node = node[path[0]].children;
        path.shift();
    }
}
Comments