I have the following data.
var data = "a.b.c.d"; //Just an example but can be more deep.
- A nested structure as a string to create a.b.c.n
Now i want to create a js object from this data like this..
{
"a":{
"b":{
"c":{
and so on till the given depth.
}
}
}
}
What i have tried
function createHierarchy( obj, group, i){
if(i === group.length){
return obj;
}
else{
if(obj[group[i]] === undefined)
{
obj[group[i]] = new Object();
}
createHierarchy(obj[group[i]], group, ++i);
}
}
Problem
This function is returning me undefined as i am sending the newly created subobject in every recursive call and since the newly created object is {} , hence the final result is undefined.
Update
I want to create the object only if it does not exist.For eg : if d already exists ill insert a value into it. else ill create it.
So this is what i added to @Tholle's answer.
if(temp[array[i]] === undefined)
temp = temp[array[i]] = {};
else
temp = temp[array[i]][name] = value;
So kindly suggest a way out.
https://jsfiddle.net/qo21eh84/2/
So,
Gives: