Given these two strings,
'1|100376|100377|100378' and
'1|100376|100377|100379|100380'
I want to create an object that looks like this:
{
id:"1",
children: {
id:"100376",
children: {
id:"100377",
children: {
id:"100378",
children: {},
id: "100379",
children: {
id:"100380",
children: {}
}
}
}
}
}
Here is the code I have,
var tree = {};
var addTree = function(aggregateId){
if(aggregateId){
var arr = aggregateId.split('|'),
remainder = aggregateId.split('|').slice(1).join('|');
arr.reduce(function(node,id){
return node[id] || (node[id] = {});
}, tree);
}
};
addTree('1|100376|100377|100378');
addTree('1|100376|100377|100379|100380');
That produces the correct nesting, but not under the keys id and children. How would I go about that?
{
"1": {
"100376": {
"100377": {
"100378": {},
"100379": {
"100380": {}
}
}
}
}
}
node.children = xxornode.id = xx?node.children = xxornode.id = xx... I get lost in adding the sub-level objects to the main tree object, and it also having multiple keys :(100379in your result appears in neither.