0

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?

4
  • The format is a little different: {'someKey': {'someSubKey1': 'value1', 'someSubKey2': 'value2', 'someSubKey3': 'value3'} } Commented Feb 1, 2017 at 20:44
  • 2
    That is not a valid object. Do you want to create an array of objects each with a single property? Or should someSubKey1, someSubKey2, etc all be part of the same object? I recommend to read a tutorial about data structure in JS: eloquentjavascript.net/04_data.html . Also, what has JSON to do with it? Commented Feb 1, 2017 at 20:46
  • 1
    I tried a lot. Could you please put the codes you tried? Commented Feb 1, 2017 at 20:48
  • I feel like an idiot, I miss the [ ] in the original post, I edited it now Commented Feb 2, 2017 at 3:06

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I feel like an idiot, I miss the [ ] in the original post, I edited it now
2

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'}
    ]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.