0

so I got this code that pushes data from an API in an array and it kinda works. If i log the array as a whole it does show the entire array, but if i try to log a specific object within the array it returns "undefined".

my code is below:

let people = [];
fetch('https://randomuser.me/api/?results=10')
    .then(function(response){
        return response.json();
    })
    .then(function(data){
        for(i=0; i<10; i++){
            let person = data.results[i];
            let x = {
                name: person.name.first + " " +person.name.last,
                picture: person.picture.large,
                age: person.dob.age,
                place: person.location.street + "<br>" + person.location.city + "<br>" + person.location.state
            }
            people.push(x);
        }
    }).catch(function(error){
            console.log('Data is not shown ' + error.message);
});


console.log(people); // works fine
console.log(people[0]); // returns undefined
console.log(people.length); //returns 0

3 Answers3

0

@ibrahimyilmaz is correct: you want to console log use your people array after your AJAX request has finished.

What you do with your array is up to you. So say you have a function that inserts the name of a person into the DOM:

function renderPersonsNameToHeader(person) {
    var header = document.querySelector('h1');
    header.innerText = person.name;
}

So your code would look like:

let people = [];

function renderPersonsNameToHeader(person) {
    var header = document.querySelector('h1');
    header.innerText = person.name;
}

fetch('https://randomuser.me/api/?results=10')
    .then(function(response){
        return response.json();
    })
    .then(function(data){
        for(i=0; i<10; i++){
            let person = data.results[i];
            let x = {
                name: person.name.first + " " +person.name.last,
                picture: person.picture.large,
                age: person.dob.age,
                place: person.location.street + "<br>" + person.location.city + "<br>" + person.location.state
            }
            people.push(x);
        }

        // Now that our `people` array is built, we can use the data!
        renderPersonsNameToHeader(people[0]);
    }).catch(function(error){
        onsole.log('Data is not shown ' + error.message);
    });
romellem
  • 5,792
  • 1
  • 32
  • 64
  • what if I need to use people[0] in a different function? because that's why i made it a global let – ruben Maesfranckx Oct 03 '18 at 20:43
  • One way to use it is to pass it as an argument to a function, that does whatever you want to do. That _sort of_ defeats the purpose of storing it in a global variable, but it works. At the end of the day, since `fetch` run asynchronously, you need to make sure the order in which your code runs is `fetch data -> store data -> *do something* with that data`. What you do and _how_ you access the data is up to you. – romellem Oct 03 '18 at 20:49
  • @rubenMaesfranckx See my edits above for one way you might accomplish that (i.e., by passing it as an argument to a function) – romellem Oct 03 '18 at 20:50
0
function logToConsole(people) {
    console.log(people); // works fine
    console.log(people[0]); // returns undefined
    console.log(people.length); //returns 0
}


fetch('https://randomuser.me/api/?results=10')
.then(function(response){
    return response.json();
})
.then(function(data){
    let people = [];
    for(i=0; i<10; i++){
        let person = data.results[i];
        let x = {
            name: person.name.first + " " +person.name.last,
            picture: person.picture.large,
            age: person.dob.age,
            place: person.location.street + "<br>" + person.location.city + "<br>" + person.location.state
        }
        people.push(x);
    }

    logToConsole(people);
}).catch(function(error){
        console.log('Data is not shown ' + error.message);
});
ibrahimyilmaz
  • 2,317
  • 1
  • 24
  • 28
0
let people = [];
fetch('https://randomuser.me/api/?results=10')
.then(function(response){
    return response.json();
})
.then(function(data){
    for(i=0; i<10; i++){
        let person = data.results[i];
        let x = {
            name: person.name.first + " " +person.name.last,
            picture: person.picture.large,
            age: person.dob.age,
            place: person.location.street + "<br>" +      person.location.city + "<br>" + person.location.state
        }
addPerson(people,x);
      }
function addPerson(array,value){
array.push(value);
}
// Run these _after_ your `for` loop
    console.log(people);
    console.log(people[0]);
    console.log(people.length);
}).catch(function(error){
    onsole.log('Data is not shown ' + error.message);
});
Osama
  • 2,912
  • 1
  • 12
  • 15