0

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);
            });
    });
0

1 Answer 1

2

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);
  1. 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);
    });
    
  2. 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Nice explaination! But I'm still in a bit of trouble with this, I made an edit up in my question, but it still doesn't give me any data. What's the reason? :)
Sorry, I made a mistake in reading the JSON data. I updated my answer.
Thanks! I think I'm going to fix this now!

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.