javascriptreactjsnode.js

Getting a list of all countries to using npm countries-list


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


Solution

  • countries is an object, not an array. If you want a list of all, your after.. for (const country of Object.values(countries)) { console.log(country.name) }

    eg.

    <script type="module">
    import {countries} from 'https://cdn.jsdelivr.net/npm/countries-list@3.1.0/+esm';
    
    for (const country of Object.values(countries)) {
      console.log(country.name);
    }
    </script>