Reputation: 1156
I'm trying to loop through a JSON array, but I'm not sure how to build the each in this case properly, any ideas?
Here is the JSON that the $.get is getting:
[{"Question":"Write your question here",
"Answers":
[{"Answers":"asd",
"Correct":false},
{"Answers":"dasdas",
"Correct":true
}
]},
{"Question":"Write your question here",
"Answers":
[{"Answers":"asdasd",
"Correct":false
}
]
}]
Here is the Jquery:
$.get("data.php", function(data){
var data = data.replace(/[\[\]']+/g, '')
$.each(data, function(i, q) {
var q = new Question(count++, data.Question);
$.each(data, function(i, val) {
q.addAnswer(data.Answers, Correct, q);
});
});
questions.push(q);
});
EDIT:
$.get("data.php", function(data){
$.each(data, function(i, val) {
var q = new Question(count++, val.Question);
questions.push(q);
});
$.each(q.Answers, function(i, val) {
q.addAnswer(val, val.Correct, q);
questions.push(q);
});
});
Upvotes: 0
Views: 100
Reputation: 86230
This line is causing a problem:
var data = data.replace(/[\[\]']+/g, '')
You're trying to call the non-existent "replace" method of an array.
In this part there are two (three) problems.
$.each(data, function(i, q) {
var q = new Question(count++, data.Question);
$.each(data, function(i, val) {
q.addAnswer(data.Answers, Correct, q);
});
});
questions.push(q);
You're calling each on an array while you iterate over the array. If you have 10 questions in your JSON, you will end up with 100 answers.
You might have meant this.
.each(val.Answers, function(i, a) {
q.addAnswer(a.Answers, a.Correct, q);
});
You're creating a variable called q
inside a function, and trying to access it outside the question. You should move the questions.push into the each function.
Upvotes: 2