I'm trying to pass json content from a local file to a variable in order to feed dropdown lists dynamically. I've got the code below that works just fine if I hard code the json data, but I struggle to initialize the variable that receives the json from the local file... I fetch it, print it in the console, but my var remains undefined afterwards.
https://jsfiddle.net/ssoj_tellig/zo85r30x/10/
// test to pass json content to var mydates:
var mydata;
fetch("{% static 'dates.json' %}")
.then(function(u){return u.json();})
.then(function(json){mydata = json; console.log(mydata)})
// test to see if mydates is correctly initialized, this should print in the console: 2018, 2019, 2020 ... not working
for (let year in mydata){
console.log(year)
}
I've read the following articles, but to no avail (I still struggle to understand how to fix it):
What is the scope of variables in JavaScript?
How do I return the response from an asynchronous call?
Many thanks for your help !