Reputation: 1144
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: []}]}]
Upvotes: 1
Views: 92
Reputation: 2285
Yes, take a look at this function which was created for that (i'm the author, by the way):
https://github.com/DiegoZoracKy/make-object-path
The code is:
var makeObjectPath = function(_src, _path, _val) {
var src = _src,
path = _path,
val = _val;
if (arguments[0] instanceof Array || typeof(arguments[0]) == 'string') {
src = {};
path = arguments[0];
val = arguments[1] || null;
}
path = (typeof(path) == 'string') ? path.split('.') : path;
var o = src;
var currentO = o;
for (var i in path) {
currentO[path[i]] = (i != path.length - 1) ? currentO[path[i]] || {} : (val) ? val : {};
currentO = currentO[path[i]];
}
return o;
}
And to use it:
makeObjectPath('root.parent.child', 'someValue');
// Output:
{
"root":{
"parent":{
"child":"someValue"
}
}
}
Upvotes: 1