I'm having a bit of trouble using data loaded from a JSON file immediately after I load it. Code below.
newdata = []
$.getJSON(file, function(data) {
$.each(data.items, function(i,item){
if (item.id != undefined) {
if (item.id === cl) {
newdata.push(item.id);
}
}
});
});
console.log(newdata);
The console.log statement doesn't return the data though, it returns an empty array []. However, if I call the variable data in my chrome debugger, it returns the correct array. How do I use data with the correct elements immediately after I create it from the JSON file?
getJSONreturns data to the callback function in asynchronous fashion. So,console.logis executed before thedatais returned.console.logis firing before your request is complete. The data is available inside the callback exactly as you'd expect. There are something like 200 questions on this exact topic on SO.