I have a data structure like so:
var questions {
'foo' : [
{
'question' : 'Where do babies come from?',
'choice' : [ 'a', 'b', 'c', 'd' ]
},
{
'question' : 'What is the meaning of life?',
'choice' : [ 'a', 'b', 'c', 'd' ]
}
],
'bar' : [
{
'question' : 'Where do babies come from?',
'choice' : [ 'a', 'b', 'c', 'd' ]
},
{
'question' : 'What is the meaning of life?',
'choice' : [ 'a', 'b', 'c', 'd' ]
}
]
}
I need to navigate and select various data contextually. I need bar and 1 in questions.bar[1].question to be variable. I have written the following and have had no success:
var quiz = $('[id*="Quiz"]');
var skill = quiz.attr('id').substring(0, 3); // 'foo' or 'bar'
var string = '';
for(var i = 0; i < questions[skill].length; i++) {
var baz = skill + '[' + i + ']'; // need to produce 'foo[0]' or 'bar[0]'
string += (
'<div>' +
'<p>' + questions[baz].question + '</p>' // need to select questions.foo[0].question or questions.bar[0] and then print '<p>Where do babies come from?</p>'
);
}
If anyone knows how to make the array name itself a variable, that would be much appreciated.
questions[skill].lengthneed to bequestions.skill.length(if you are sure thatskillis coming asfooorbar)skillpropertyquestions.skillis undefined. The correct code isquestions[skill].length