0

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.

4
  • 2
    questions[skill].length need to be questions.skill.length (if you are sure that skill is coming as foo or bar) Commented Jan 15, 2018 at 5:18
  • @AlivetoDie that doesn't look right at all. There is no skill property Commented Jan 15, 2018 at 5:20
  • @phil in his code he created that variable and writen there that it's coming like foo or bar Commented Jan 15, 2018 at 5:21
  • @AlivetoDie yes, but questions.skill is undefined. The correct code is questions[skill].length Commented Jan 15, 2018 at 5:22

1 Answer 1

7

The following should do the trick; you just need to pull the array value as you normally would:

var baz = questions[skill][i]; // will be `foo[i]` or `bar[i]`

This works because questions[skill] is a reference to the array, whose elements can then be accessed as usual. So then you would simply do the following to pull the question text:

'<p>' + baz.question + '</p>'
Sign up to request clarification or add additional context in comments.

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.