I'm trying to pass a JSON in a variable. The fetch() prints out the JSON correctly in the console, but the for loop shows that the variable is empty (undefined). What am I doing wrong?
var mydates;
fetch("{% static 'dates.json' %}")
.then(function(u){return u.json();})
.then(function(json){mydates = json;})
.then(function(){console.log(mydates);}) //The json is printed in the console just fine
for (let year in mydates){ // This should print in the console 2018, 2019, 2020
console.log(year) // but instead mydates is marked as undefined
};
My dates.json file looks like this:
{
"2018": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week9","week10","week11"]
},
"2019": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week9","week10","week11"]
},
"2020": {
"January": ["week1","week2","week3","week4"],
"February": ["week5","week6","week7"],
"March": ["week8","week9","week10","week11"]
}
}
Many thanks for your help!