F
F
furcifer2018-06-09 23:13:00
JavaScript
furcifer, 2018-06-09 23:13:00

Why does "data.foreach is not a function" happen like this?

Hello! Can you please tell me how to fix this error, "data.foreach is not a function"?
There is api. We need to get the title elements and output to the console

var api = new XMLHttpRequest();
api.open("GET", "http://swapi.co/api/films/", true);

api.onload=function(){
  var data=JSON.parse(this.response);
  
  data.forEach( film => {
    console.log(film.title);
  });
}
api.send();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2018-06-09
@furcifer

The fact is that the array of films, if you look at , is contained not in the root object of the response, but in the field results.
Those. you need to change to:data.results.forEach( film => {

I
Ihor Bratukh, 2018-06-09
@BRAGA96

If you need to iterate over the answer, then why not do it right away when parsing.

var data = JSON.parse(response, function(key, value) {
  console.log(key, value);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question