For in an AJAX array

0

I get the data from an API with an array that parses it with pure js.

This array returns me more than one object I'm currently viewing only in the browser's console.log. I do not know how to make a for in pure js. How do I make a for and then display the data of this array on the page with the objects separated. When I get one I do the following:

    if(xhr.status == 200){


      let curso = xhr.responseText;
      curso = JSON.parse(curso);

      let video = '';
      video += curso.video;
      document.querySelector('#video').innerHTML = video;

      let descricao ='';
      descricao += curso.descricao;
      document.querySelector('#curso-descricao').innerHTML = descricao;

    }

In this way it displays the video data and description, but it is only with one object. How do I do this same action to list objects in my frontend using pure js?

    
asked by anonymous 04.05.2018 / 16:50

3 answers

0

I did it this way and it worked:

if(xhr.status == 200) {
  let aulas = xhr.responseText;
  aulas = JSON.parse(aulas);

  let x = document.querySelector('#videos');
  aulas.map(item => {
    x.innerHTML += '<a href="responde-exercicio.php?id=' + item.id + '"><span>' + item.video + '</span></a>';
  });
}
    
05.05.2018 / 13:18
0

It can be done as follows:

for(var i=0; i <= curso.length; i++){
  //Faça o que quiser acessando os objetos do array pelo indice
  //utilizando o i como exemplo abaixo.

  console.log("video: " + curso[i].video);
  console.log("descricao : " + curso[i].descricao);
}

One tip is to always check if there is anything in the array:

if(curso !== null && curso !== undefined && curso.length > 0 ){
//o for vai aqui
}
    
04.05.2018 / 17:05
0

You can use forEach for this.

In this example we will use your variable video :

video.forEach(function(curso) {
    var retornoVideo = document.querySelector('#video');
    return retornoVideo.innerHTML += curso.video;
});

See if this works and tell me if you helped or not.

    
04.05.2018 / 17:08