1

I have a function foo that takes in an array of objects called locations and has a string, fourSquareUrl, containing information to access the Foursquare API. I grab the data from the API and push it to the locationData array.

When I try to access an index of the array, locationData[i], I get undefined. But when I console.log(locationData); the array is displayed correctly. Thanks for your help!

var locationData = [];
function foo(locations) {
    for (x in locations) {
        var fourSquareUrl = 'API information';
        $.getJSON(fourSquareUrl, function(data) {
                var foursquareLocation = data.response.venues;
                if(foursquareLocation) {
                    var item = foursquareLocation[0];
                    if (item) {
                        var address = item.location.formattedAddress;
                        locationData.push(address);
                    }
                    else {
                        var noAddress = "No location data available";
                        locationData.push(noAddress);
                    }
                }
        })
    }
}

// works correctly
console.log(locationData);

// results in 'undefined'
console.log(locationData[0]);
rdtn
  • 23
  • 2
  • Yes is the async function, you should add the console.log inside the callback function (block `$.getJSON(fourSquareUrl, function(data) {`) to get the result. – vitomd Nov 08 '16 at 22:05

1 Answers1

0

The address which is retrieved is probably undefined. You should check this way if it is the case: var locationData = [];

function foo(locations) {
    for (x in locations) {
        var fourSquareUrl = 'API information';
        $.getJSON(fourSquareUrl, function(data) {
                var foursquareLocation = data.response.venues;
                if(foursquareLocation) {
                    var item = foursquareLocation[0];
                    if (item) {
                        var address = item.location.formattedAddress;
                        if (!address) {
                          console.log('Empty address is returned');
                        }
                        locationData.push(address);
                    }
                    else {
                        var noAddress = "No location data available";
                        locationData.push(noAddress);
                    }
                }
        })
    }
}

// works correctly
console.log(locationData);

// results in 'undefined'
console.log(locationData[0]);
Nicolas Henneaux
  • 11,507
  • 11
  • 57
  • 82