JSON: How to add dynamic sub objects to dynamically created main object in Json.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-22-2016 05:30 AM
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?
- Labels:
-
Scripting and Coding

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-22-2016 06:08 AM
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-22-2016 11:24 PM
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.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-23-2016 08:57 AM
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 : { }
]};
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-26-2016 12:37 AM
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 }
]};