1

I'm using this site: https://jsonplaceholder.typicode.com/users/ as ajax practice with javascript.

I'm trying to get a certain property value from multiple IDs.

Let's use phone for example.

How can I loop through all the files and get every id and his phone?

Like this:

id : 1 phone : 123

id : 2 phone : 124

I'm trying to use for...in but I can't really get the hang of it rather than looping through only 1 of them.

function callToServer(param) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      //if (this.readyState == (4) Done && this.status == (200) All good) {
      if (this.readyState == 4 && this.status == 200) {
        res = JSON.parse(this.responseText);
        for (var key in res) {
          demo.innerHTML += `${key} : ${res[key]}<br>`;
        }
      }
    }
// notice that I used "9" after to loop only through 1 :)
xhttp.open("GET", "https://jsonplaceholder.typicode.com/users/9", true);
      xhttp.send();
}
cpru
  • 78
  • 1
  • 7
Nyaaaaaaaa
  • 21
  • 6

2 Answers2

0

Access your data using res[key].id

function callToServer(param) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        res = JSON.parse(this.responseText);
        for (var key in res) {
          demo.innerHTML += `${key} : ${res[key].id}<br>`;
        }

      }
    }
crg
  • 4,284
  • 2
  • 29
  • 57
0

Loop over the array and get the id and phone properties of each element. You can use forEach() for this rather than a for loop. See Why is using "for...in" for array iteration a bad idea?

function callToServer() {
  let xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      let html = '';
      let res = JSON.parse(this.responseText);
      res.forEach(user => demo.innerHTML +=
        html += `id ${user.id}: phone ${user.phone}<br>`;
      )
      demo.innerHTML = html;
    }
  }

  xhttp.open("GET", "https://jsonplaceholder.typicode.com/users", true);
  xhttp.send();
}
Barmar
  • 741,623
  • 53
  • 500
  • 612