1

I'm trying for learning purposes to get data from an open API for quizzes.

What I started is to get the data from API and in console.log() see if I'm doing right. I'm parsing the URL before the foreachbut I'm getting the error:

Uncaught TypeError: data.forEach is not a function

This is the sample code I'm trying and I understood that I have to parse the JSON first before the foreach but is not working for me and cannot see why

/**
 *
 * @GET url of the API https://opentdb.com
 *
 */
// Creating a request variable with the OBJ inside
var request = new XMLHttpRequest();
// Opening a GET request to the API
request.open("GET", "https://opentdb.com/api.php?amount=10");
// Load the request
request.onload = function() {
    // Accessing the JSON data
    var data = JSON.parse(this.response);
    // Checking if we have status 200 good to go otherwise error
    if (request.status >= 200 && request.status < 400) {
        // Looping the data
        data.forEach(results => {
            console.log(results.question);
        });
    } else {
        // Showing error for the status
        console.log("error");
    }
};
// Request send
request.send();

EDIT Showing the asked data content from console.log(data)

Result of console.log()

4
  • 1
    What happens if you console.log out data? Commented Oct 18, 2019 at 8:43
  • maybe your data is not array or it's getting null Commented Oct 18, 2019 at 8:43
  • I edit adding the screenshot of the console.log(data) Commented Oct 18, 2019 at 8:49
  • For future reference: Your error message gives you a big clue. data.forEach is not a function. forEach is a function only on arrays, so that means your data object is not an array, so you should look to see what it is. Commented Oct 18, 2019 at 9:34

6 Answers 6

3

Speaking just for your example: If you open the API Url yourself, you can see that the resulting data is not an array, but an object like:

{
    "response_code": 0,
    "results": [
        {
            "category": "Entertainment: Film",
            "type": "multiple",
            "difficulty": "medium",
            "question": "Who played Batman in the 1997 film &quot;Batman and Robin&quot;?",
            "correct_answer": "George Clooney",
            "incorrect_answers": [
                "Michael Keaton",
                "Val Kilmer",
                "Christian Bale"
            ]
        }
    ]
}

That means you should use data.results to itterate over the data.

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

2 Comments

Where I should use data.results? ``` data.forEach(data.results => { console.log(results.question); }); ``` This not work
data.results.forEach(item=>{console.log(item)}) this will work fine
1

Seems you are accessing whole response, instead get results this.response.results:

var data = JSON.parse(this.response).results;

if (request.status >= 200 && request.status < 400) {
    data.forEach(results => {
        console.log(results.question);
    });
}

3 Comments

I don't see a "data" property within that returned object
This is not working and not seems to be an aright solution.
@jacub I have updated with results as initially there was no screenshot attached. data was a guess.
1

The data you're getting back from the server is an object, not an array. .forEach is only available on arrays.

However there is an array within that data called "results", and the objects within that contain the "question" properties which you're interested in.

So the fix is simple, just iterate over the "results" array instead:

data.results.forEach(result => {
  console.log(result.question);
});

Comments

1
  var data = JSON.parse(this.response);
    // Checking if we have status 200 good to go otherwise error
    if (request.status >= 200 && request.status < 400) {
        // Looping the data
        data.forEach(results => {
            console.log(results.question);
        });
    } else {
        // Showing error for the status
        console.log("error");
    }
};

Since your data is not an array it cant irterate and forEach function is used to iterater over an array. Assuming your response consists any array as

 responseData: {
                sc: "0000|Success",
                 clientId: "ptm",
                  reportStatus:[
                      {reportName: "sale_report", 
                          id: "275", 
                          status: "AVAILABLE"},
                          {reportName: "sale_report", 
                          id: "276", 
                          status: "PENDING"}]
}

responseData.reportStatus fetch the value and then iterate over it.

responseData.reportStatus.forEach((item,index,arr)=>{
  console.log(item);
})

this will fetch you with all the items inside array.

Comments

1

I have modified the code actually you are looping on wrong property you should loop on the results.

 var request = new XMLHttpRequest();
    // Opening a GET request to the API
    request.open("GET", "https://opentdb.com/api.php?amount=10");
    // Load the request
    request.onload = function() {
      // Accessing the JSON data
      var response = JSON.parse(this.response);

      // Checking if we have status 200 good to go otherwise error
      if (request.status >= 200 && request.status < 400) {
        // Looping the data
        var data = response.results;
        data.forEach(results => {
          console.log(results.question);
        });
      } else {
        // Showing error for the status
        console.log("error");
      }
    };
    // Request send
    request.send();

Working code is at below https://codesandbox.io/s/white-breeze-8w8jy

Comments

1
    var request = new XMLHttpRequest();

    request.open("GET", "https://opentdb.com/api.php?amount=10");

   request.onload = function() {  
   var data = JSON.parse(this.response);
   if (request.status >= 200 && request.status < 400) {
    data.results.forEach(results1 => {
        console.log(results1.question);
    });
   } else {        
    console.log("error");
  }
  };

 request.send();

I have tried your code and you are missing results between data and forEach. After that it is logging question in console.

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.