问题
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.
回答1:
var data = "a.b.c.n";
var array = data.split(".");
var result = {};
var temp = result;
for(var i = 0; i < array.length; i++) {
temp = temp[array[i]] = {};
}
console.log(result);
回答2:
function BuildObj(string) {
var obj = {};
var params = string.split(".");
for(var i=params.length-1;i>=0;i--) {
last = obj;
obj = {};
obj[params[i]] = last;
}
return obj;
}
So,
buildObj("a.b.c.d");
Gives:
{
"a": {
"b": {
"c": {
"d": {}
}
}
}
回答3:
var data = "a.b.c.n";
var array = data.split(".");
var last = {};
var temp = {};
for (var i = array.length - 1; i >= 0; i--) {
temp = {};
temp[array[i]] = last;
last = temp;
}
console.log(last);
https://jsfiddle.net/qo21eh84/2/
来源:https://stackoverflow.com/questions/31390915/how-to-create-a-complex-nested-js-object-dynamically