I have a list:
var list = ['parent-element', 'child-of-previus-element-1', 'child-of-previus-element-2'];
where each next element in the array is a child of the previous.
I want to transform this list into a tree structure, e.g.:
{
"parent-element": {
"childrens": [{
"child-of-previus-element-1": {
"childrens": [{
"child-of-previus-element-2": {
"childrens": []
}
}]
}
}]
}
}
I have tried:
var list = ['parent-element', 'child-of-previus-element-1', 'child-of-previus-element-2'];
var tree = {};
for (var i = 0; i < list.length; i++) {
if( list[i-1] && tree[list[i-1]] ){
tree[list[i-1]].childrens[list[i]] = {"childrens": []};
} else {
tree[list[i]] = {
"childrens": []
};
}
}
console.log( JSON.stringify(tree) );
but the output is:
{
"parent-element":{
"childrens":[]
},
"child-of-previus-element-2":{
"childrens":[]
}
}