Homer Homer - 28 days ago 6
Javascript Question

how to concatenate (variable + object key names) to get the object values in dot notation

Assuming I've a JSON object like this:

var myObj = {
'question1': {
'option1': 'foo',
'option2': 'bar',
'option3': 'baz'
},
'question2': {
...
},
'question3': {
...
}
};


And since its children always has a number in its keys, I want to do a loop and concatenate the loop's index to the object keys, and get the values in the dot notation method...

So, I guess to get the values, I need to do some thing like this:

myObj.'question'+i


How can I do the concatenation right?

Answer

Simply do

myObj['question'+i]

This is because the dot operator would not accept string with it as per javascript. So you will have to use square brackets instead which is often used to access properties of an object dynamically.