I have a path(as a string) like
A/B/C/D
. I want to represent it as a JSON object as follows :
{
A:{
B:{
C:D
}
}
}
Now lets say I add a path
A/B/C/X
then the JSON should look like
{
A:{
B:{
C:[D,X]
}
}
}
So what I do is when I get the path, I split it and store in an array as follows
var struct = {};
var path = $scope.path.split("/"); //assuming $scope.path holds the path
for(var i =0;i<path.length-1;i++)
{
struct[path[i]] = path[i+1];
}
However this leads to json as {A: "B", B: "C", C: "D"}.
How do I fix this? Is there a recursive way to do this?
EDIT : My previous schema would lead to error. As KevinB suggested, I am updating the schema to something like [{name: 'A', children: [{name: 'B', children: []}]}]
C: DandC: Xin theBobject,Cwould need to be converted to an array of[D,X], orBto be an array of[{C:D},{C:X}][{name: 'A', children: [{name: 'B', children: []}]}]