How to create a complex/nested js object dynamically?

我们两清 提交于 2019-12-11 09:24:33

问题


I have the following data.

var data = "a.b.c.d"; //Just an example but can be more deep.

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!