no name
no name

Reputation: 1

Undefined when parsing data and getting specific objects

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.

Upvotes: 1

Views: 64

Answers (1)

code
code

Reputation: 6329

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}`);
}

Upvotes: 2

Related Questions