I have installed the package: npm install countries-list
This contains:
Module exports continents, countries, languages and utility functions.
if I do
import { continents, countries, languages } from 'countries-list'
and do
console.log(countries)
, I get an array containing all the countries, capital, continent etc.
So fx, I want to create dropdown box where I populate it with countries.
If I do
for (let i=0; i < countries.length; i++) { console.log(countries[i]) }
I get undefined. Hence I can’t do countries[i].name
etc. I also tried doing
countries.forEach((val) => {
...
{)
which also gives an error. If I want to get a specific country, I can do countries['FR']
which in this case will give me France. But I want to get all countries, and in some cases, their capital or continent. How can I do this?
I found the info here: https://www.npmjs.com/package/countries-list
But I failed to find any help or documentation on what I want
If anyone knows a better way/package that will deliver me all countries with the languages etc, please share
3
Answers
Use a for..in statement like:
countries is an
object
, not anarray
. If you want a list of all, your after..for (const country of Object.values(countries)) { console.log(country.name) }
eg.
For a more detailed answer, when you call
countries['UA']
, you are accessing the key-value pair with the key of'UA'
, thus returning to you the object that is the value for that key.Your
for
loop declaresi
to be equal to 1, and increment each iteration. There is no key in the table for1
. This would work if this was an array, where you could access each element by the index number, (which is why we name iti
usually).Iterating through an object it is actually quite similar to an array though. Using the
Object.entries(countries)
method, you can pass your object and it will return an array of a its own enumerable string-keyed property key-value pairs.Object.entries() documentation
The reason that
countries.map()
doesn’t work here is because themap
method belongs toarrays
and notobjects
.You can still manually access the values in the same way however. For example:
would return
['French']
Hope this helps!