Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Unable to loop through the list

Hello there,

As always I like to break things around and use my code rather than what is there on the workspace. Also, I wanted to review the previous lesson with Dave here:

https://teamtreehouse.com/library/processing-json-data-2

I am trying to loop through the list we import from the URL, and print a very simple HTML list that includes astronauts names in the HTML page.

The code is the following:

//sending a request.

function send () {

   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function () {

       if (xhr.readyState === 4 && xhr.status === 200) { 
           let astronauts = JSON.parse(xhr.responseText); 

           //creating a list with the information we get from the link

           var listHTML = '<ul class="list">'

           for (let i = 0; i < astronauts.length; i++) { 

           listHTML += "<li>" + people[i].name + "</li>"
  }

            listHTML += '</ul>' //closing string

  console.log(astronauts);

// Here I have selected the DIV in the HTML file. I am printing the list there.

       document.getElementById('people').innerHTML = listHTML;
     }
         };


 xhr.open("GET", 'http://api.open-notify.org/astros.json');
  xhr.send();

  }

//this is the button that should fire the function:

btn.addEventListener('click', (event) => {

send () 

});

Somewhat I am unable to loop through what I get from the server: "{message: "success", people: Array(6), number: 6}".

This array of arrays contains 6 "people" , which are:

1: {name: "Nick Hague", craft: "ISS"} 2: {name: "Christina Koch", craft: "ISS"} 3: {name: "Alexander Skvortsov", craft: "ISS"} 4: {name: "Luca Parmitano", craft: "ISS"} 5: {name: "Andrew Morgan", craft: "ISS"}

What am I doing wrong?

2 Answers

hello alexander. it seems that you are trying to loop on an object. you actually need to get to the array.

let astronauts = JSON.parse(xhr.responseText); 
let arr = astronauts.people;
// here just change arr.length in your loop. 

i hope this solves your issue.

anthony amaro it worked like a charm! Thanks a lot!