0

So, i'm working with the following data...

var data = {"questions": {"question0": "what?", "question1": "why?", "question2": "where?"}};

and trying to loop through all questions, like so...

for (n = 0; n < 5; n++) {
   var value = "question"+n;
   var tracker = data.questions.value;
   console.log(tracker);
}

the problem is that i'm not sure how to declare value as a variable within tracker. Right now it's just looking for value nested within questions and not the actual output of var value.

Halp.

1 Answer 1

1

You can use bracket [] to wrap a variable as key:

var data = {"questions": {"question0": "what?", "question1": "why?", "question2": "where?"}};

for (n = 0; n < 5; n++) {
   var value = "question"+n;
   var tracker = data.questions[value];
   console.log(tracker);
}

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.