i have a problem in retrieving json objects. how to retrieve the objects inside the "choices" key object? thanks for your help...
-
1There are probably dozens of questions just like this one on SO every day. Do some research and try something FCOLDexygen– Dexygen2014-01-30 14:35:03 +00:00Commented Jan 30, 2014 at 14:35
-
thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very muchymtExpo– ymtExpo2014-01-30 17:26:16 +00:00Commented Jan 30, 2014 at 17:26
Add a comment
|
3 Answers
Like so (to loop)
for (var i = 0; i < data.questions.length; i++) {
console.log(data.questions[i].choices.a);
console.log(data.questions[i].choices.b);
}
1 Comment
ymtExpo
thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much
for (var i=0; i<questions.length; i++) {
var choices = questions[i].choices;
console.log(choices.a);
console.log(choices.b);
}
1 Comment
ymtExpo
thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much
Assuming you have a var assigment like var myobj = { ... } where ... is your json object in the post, then you would access all the choices data points like this:
myobj.questions[0].choices.a
myobj.questions[0].choices.b
myobj.questions[1].choices.a
myobj.questions[1].choices.b
Are you asking something more specific about how to loop through all questions and choices?
Update: After your comment, I think you might be looking for something more like this:
for (var qi=0; qi < myobj.questions.length; qi++) {
var q = myobj.questions[qi];
console.log(q.ques);
for (var choiceKey in q.choices) {
console.log(" " + choiceKey + " --> " + q.choices[choiceKey]);
}
}
Simply replace the console.log() statements with whatever logic you need. The output of running the above code on your example JSON is this:
how old are you?
a --> 19
b --> 20
question two?
a --> answer1
b --> answer2
1 Comment
ymtExpo
thank you but i did this before and now what i want to do is to get to the next level where in i want to get the objects inside the "choices" dynamically, so that even there are lots of choices i wont bother to get the objects manually. thank you very much