I am working with an api in javascript to return some healthcare data to be analyzed and visualized. I created a function get_data()
to access the data so it can be used elsewhere in the script:
function get_data() {
console.log(vaccination_data[0]);
var vax_data = vaccination_data[0];
console.log(vax_data.city)
return vax_data
}
This works well within the function and I can log the data and it's elements to console. The problem I'm having is when I try to assign the return
variable vax_data
to a variable outside the function with var data = get_data()
I am getting the error:
"<a class='gotoLine' href='#60:22'>60:22</a> Uncaught TypeError: Cannot read properties of undefined (reading 'city')"
I have tested with a simple function and it works well, example:
function a() {
var str = "first";
return str
}
var string = a()
console.log(string)
Can anyone tell me why it works differently from the data that is being returned from the api?
Full code:
var vaccination_data = [];
$.ajax({
url: "https://health.data.ny.gov/resource/nvtm-yit2.json",
type: "GET",
data: {
"$limit" : 5000,
"$$app_token" : 'aGFbKDOg0gCeCm2c9Od2EsFjL'
}
}).done(function(api_data) {
//console.log(api_data)
vaccination_data = api_data;
get_data();
});
function get_data() {
console.log(vaccination_data[0]);
var vax_data = vaccination_data[0];
console.log(vax_data.city)
return vax_data
}
var data = get_data()
console.log(data)