Basically the title. I'll try to be as clear as I can be. I'm trying to run a for loop on two arrays after fetching json data (not on the fetched json object). The intent is to create a json output of canada's provinces and cities -
{
"state_name": ["city_name", "city_name"],
"state_name": ["city_name", "city_name"],
}
something like above
This is the code:
var canada = []; //will store all canada state names
var canadaObject = []; //will store the whole object that contains state name, city name, country code, and country name
var finalJson = "{ ";
fetch("https://link/to/json/file.json")
.then((response) => response.json())
.then((json) => {
//this for loop segregates Canada's data from other countries in the json response
json.forEach((object) => {
if (object.country_name == "Canada") {
canadaObject.push(object);
if (!canada.includes(object.state_name)) {
canada.push(object.state_name);
}
}
});
});
//want to use this for loop to compare state names from the canada and canadaObject variables to get cities from the same states
for (const property in canadaObject) {
//But nothing in here gets executed
console.log(property.name);
console.log("why is this not printed?");
}
console.log(finalJson);
This is the code in jsfiddle. I've also debugged in the browser, but the code skips to after the for loop. I'm a beginner, so think it's probably something I don't know yet or maybe I'm doing something wrong? If so, can anyone point me in the right direction?