I am facing an issue when trying to reference my imported JSON data. The problem arises when I attempt to access the data outside of a FOR loop, resulting in the error message "Uncaught TypeError: Cannot read property 'Tname' of undefined"
The following code snippet works as intended:
for (var i in towns) {
if (i == 1) {
ctx.fillText(towns[i].Tname, 0, 0);
}
}
However, the next line triggers an error with the message "Uncaught TypeError: Cannot read property 'Tname' of undefined", placed right after the above loop.
ctx.fillText(towns[1].Tname, 0, 0);
Despite trying various approaches, all attempts have failed so far. The output for "towns[1]" is displayed as "[Object Object]".
For those who are curious, here is a snippet from the towns.json file:
{"towns":[
{"Tid":"2057277", "Tname":"York"},
{"Tid":"2057575", "Tname":"Yanchep"}
]}
This portion of code handles the conversion to towns[] using JSON:
var towns[];
$.getJSON('towns.json', function(data) {
for (var i in data.towns) {
towns[i] = data.towns[i];
}
});