Reputation: 431
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.
Upvotes: 0
Views: 57
Reputation: 214987
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);
}
Upvotes: 1