Home > OS >  Can't extract Data with For Loop (JavaScript / Fetch)
Can't extract Data with For Loop (JavaScript / Fetch)

Time:08-10

Why can't I extract the fields that I want from the for loop?
Console Log
JSON Data

document.addEventListener('DOMContentLoaded', function() {
      let user = 'example';
      fetch(`/jsonresponse/${user}`)
        .then(response => response.json())
        .then(data => {

          // The line below works and prints the username
          console.log(data['UsersInfo'][0].username)

          // Doesn't work in a for Loop
          for (let i = 0; i < data.length; i  ) {
            console.log(data['UsersInfo'][i].username);
          }
        });

Any hints would be appreciated

CodePudding user response:

Your issue is in for loop you need to loop over data["UsersInfo"] not just data

                        vvvvvvvvvvvv
for (let i = 0; i < data["UsersInfo"].length; i  ) {
  console.log(data["UsersInfo"][i].username);
}

it's better to store user users in array and loop over them with for..of

const users = data["UsersInfo"];
for (const user of users) {
  console.log(user.username);
}
  • Related