0

I am parsing an array of JSON objects but cannot for the life of me figure out why I cannot access an individual object within the array. I can log the the entire array but when I attempt to access a specific object within the array it returns undefined.

  function fetchContacts(i) {
  var request = new XMLHttpRequest();
  request.open("GET", contactURL[i]);

  request.onload = function() {
    info = JSON.parse(request.responseText);
    contactData[i] = info;
  };
  request.send();
};

btn.addEventListener("click", function() {
  for (i = 0; i < contactURL.length; i++) {
    fetchContacts(i);
  }
  console.log(contactData[0]); // returns undefined
  console.log(contactData) // returns JSON objects in an array
});
brett
  • 1
  • 1
  • Is it possible that you are storing the value of `undefined` in the first slot of `contactData` perhaps the parse fails for the first url – spectacularbob Jun 20 '18 at 20:04
  • I took a quick look and wasn't able to figure out the exact reason, but it seems to have something to do with the asynchronous call. Check out this codepen where, if you add a timeout around the console.logs, it displays element[0] properly: https://codepen.io/anon/pen/JZLRZw?editors=1010 – emmzee Jun 20 '18 at 20:18

0 Answers0