Brandon
Brandon

Reputation: 1

JSON objects wont transfer into js array using ajax

I get undefined when i try to console.log it

var farr = [];
$.ajax({
    url: "https://whispering-cliffs-33347.herokuapp.com/employees",
    type: "GET",
    contentType: "application/jsonp"
}).done(function(employees) {
    for(let i in employees){
        farr.push(employees[i]);
    }
})
console.log(farr[8]);

Any ideas?

Upvotes: 0

Views: 32

Answers (2)

Aaditya Thakkar
Aaditya Thakkar

Reputation: 1820

You can not iterate the object with standard for loop. To be able to do that, you should first get object keys in an array and iterate over that.

const keys = Object.keys(employees);
keys.forEach((i) => {
     farr.push(employees[i]);
 }
 console.log(farr[8]);. // You should put this in the call back itself

Or you can directly iterate over the object using lodash's forEach.

Upvotes: 0

brk
brk

Reputation: 50291

console.log(farr[8]); will be executed even before the response is available.So in first done push all the elements in the local array & once that is done in the next done log the value

var farr = [];
    $.ajax({
        url: "https://whispering-cliffs-33347.herokuapp.com/employees",
        type: "GET",
        contentType: "application/jsonp"
    }).done(function(employees) {
        employees.forEach(function(item){
            farr.push(item)
        })
    }).done(function(elem){
        console.log(farr[8]);
    })

Upvotes: 1

Related Questions