As I work on converting a 2-character country code to its longer name, it seems logical to me to save this information in an external JSON file rather than embedding it directly into the script. However, while I am able to successfully read the JSON data into an array, I seem to be encountering a scoping issue:
var countries = {};
$.getJSON("countrycodes.json", function(data) {
for (let i in data)
countries[data[i].code] = data[i].longname;
console.log(countries["MX"]) // outputs "Mexico"
});
console.log(countries["MX"]) // returns Undefined
The contents of my countrycodes.json file are as follows:
[
{"code" : "US", "longname" : "United States"},
{"code" : "CA", "longname" : "Canada"},
{"code" : "MX", "longname" : "Mexico"},
{"code" : "RU", "longname" : "Russia"}
]