JSON: How to add dynamic sub objects to dynamically created main object in Json.

kumar_bsc
Kilo Explorer

var mainObj = [

  {

  name: 'someName',

  some_data: [

  {

  someOtherName: 'Some',

  someOtherNum: '112'

  },

  {

  someOtherName: 'A2325A',

  someOtherNum: '132'

  }

  ]

  },

  {

  name: 'someName1',

  some_data: [

  {

  someOtherName: 'Some',

  someOtherNum: '112'

  },

  {

  someOtherName: 'A2325A',

  someOtherNum: '132'

  }

  ]

  }

]

This particular content is hard coded, I want this to be generated dynamically from an array where all this data is being stored. Can this be done?

5 REPLIES 5

Chuck Tomasi
Tera Patron

Hi Mathu,



Can you clarify what you mean by dynamically created? You've got an object with an array of stuff in it. Each array element has a couple properties. What's next?


kumar_bsc
Kilo Explorer

Assume I have an array as follows - var mainArray = new Array("mainObj1", "mainObj2", "mainObj3");



So the main object itself needs to be created dynamically. And sub objects from another array needs to be added under main object.


Hi Muthu,



I'd do it something like this:



var myObj = {};


var mainArray = new Array("mainObj1", "mainObj2", "mainObj3"


for (var i = 0; i < mainArray.length; i++) {


        myObj[mainArray[i]] = {};


        // now populate myObj.mainObj1.whatever with what you want (the loop will substitute mainObj1 with 2, and 3)


}



End result:



myObj = {[


    mainObj1 : { },


    mainObj2 : { },


    mainObj3 : { }


]};


Hi Chuck,



How do I get output as below, Dynamically as you have shown above.


Say subNames is an another array var subNames = new Array("sub1", "sub2", "sub3");



myObj = {[


    mainObj1 : {


                                      name: name1,


                                      subNames: [


                                                    {


                                                              someOtherName: 'Some',


                                                              someOtherNum: '112'


                                                    },


                                                    {


                                                              someOtherName: 'Some',


                                                              someOtherNum: '112'


                                                    }


                                ]


},


    mainObj2 : {


                                      name: name2


        },


    mainObj3 : { same }


]};