1

I am using leaflet 1.7.1 and successfully loaded JSON file from the local memory of my machine. I have an object which looks like this:

covid = {"AFG":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KOR":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KGZ":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
....} 

What I want to do is to get countries by their ISO country code(e.g. KOR, KGZ etc). Even after converting to object file I cannot get by index like covid[0] but it is not working. I am new to JS and cannot really handle the data.

1 Answer 1

2

Notice it's not called JavaScript Array Notation, but rather JavaScript Object Notation.

The problem: covid is NOT an array. It's an object. Here's a great read. To fix your problem, you refer to the actual name.

To use it in your project, you could loop through the object and use it like so:

for (let isoCountryName in covid) {
  console.log(`${isoCountryName}`);
}

Here's a demo:

var covid = {"AFG":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KOR":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6},
"KGZ":{"continent":"Asia","location":"Afghanistan","population":38928341.0,"population_density":54.422,"median_age":18.6}};
for (let isoCountryName in covid) {
  console.log(`ISO country name: ${isoCountryName}`);
}

Sign up to request clarification or add additional context in comments.

7 Comments

Should I use Ajax for this? In my console it is showing nothing
Heey, thank you. It worked. The problem was I copied the parsed data into new variable which wasn't really object(wrongly copied). I tried with original parsed object and it worked great!
@noname AJAX for what?
I run into another problem which is that isoCountryName is not part of an object anymore. I mean if I have data (eg. isoCountryName.data) in KOR(which is isoCountryName) it return underfined. Is there anything I can do?
You can get the entire object under the country like this: covid.AFG or covid["AFG"].
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.