NewJsGuy
NewJsGuy

Reputation: 113

javascript - Dynamically create nested json objects

I want to be able to create and object like this

{'someKey':
    [{'someSubKey1': 'value1'},
    {'someSubKey2': 'value2'},
    {'someSubKey3': 'value3'}]
}

I tried a lot but I think I'm missing something

first of all I created an array and pushed the elements, then I did a JSON parse and finally a join (","), but the result wasn't the expected.

Some help?

Upvotes: 0

Views: 1476

Answers (2)

Alex Svetkin
Alex Svetkin

Reputation: 1409

If you need to access your data structure like myvar.someKey.someSubKey1, consider this structure:

{   'someKey': 
    {
        'someSubKey1': 'value1',
        'someSubKey2': 'value2',
        'someSubKey3': 'value3'
    }
}

If you'd like to go with myvar.someKey[0].someSubKey1, try this:

{'someKey': 
    [
        {'someSubKey1': 'value1'},
        {'someSubKey2': 'value2'},
        {'someSubKey3': 'value3'}
    ]
}

Upvotes: 2

Abhinav Galodha
Abhinav Galodha

Reputation: 9928

You need to put the contents in an array with []. Wrap you inner json inside an array like

var obj = {'someKey': [
    {'someSubKey1': 'value1'},
    {'someSubKey2': 'value2'},
    {'someSubKey3': 'value3'}]
}
console.log(obj);

Upvotes: 3

Related Questions