boyjarv's avatar

Javascript how to get Country code from country name?

Hi,

I would like to get the country code from a country name using plain vanilla javascript?

United Kingdom = UK
South Africa = ZA
0 likes
13 replies
boyjarv's avatar

@chrisgrim this isn't working?!

races.forEach((race) => {
      fetch(`https://restcountries.eu/rest/v2/name/${race.Circuit.Location.country}`).then(resp=>{
            return resp.json();
      }).then(json=>{
        var country = json[0].alpha2Code;
        console.log('country', country);
      })
}
boyjarv's avatar

I tried this:

fetch("https://restcountries.eu/rest/v2/name/kenya").then(resp=>{
      console.log('resp: ',resp);
      return resp.json();
}).then(json=>{
      console.log('Kenya: ',json[0].alpha2Code);
})

Can't get anything logged out?!

boyjarv's avatar

ok so I have created a country list array: I just want to filter out my

country:

races.Circuit.Location.country

and return code3

const countryListAllIsoData = [
	{"code": "AF", "code3": "AFG", "name": "Afghanistan", "number": "004"},
	{"code": "AL", "code3": "ALB", "name": "Albania", "number": "008"},
	{"code": "DZ", "code3": "DZA", "name": "Algeria", "number": "012"},
	{"code": "AS", "code3": "ASM", "name": "American Samoa", "number": "016"},
tykus's avatar
tykus
Best Answer
Level 104

@boyjarv If you have an Array, you can find an element using a callback, e.g.:

let found = countryListAllIsoData.find(country => country.name === races.Circuit.Location.country);
let code = found ? found.code3 : 'n/a';
chrisgrim's avatar

@boyjarv To find the country and return the code I would use

countryListAllIsoData.find( country => country.name === 'Algeria').code
tykus's avatar

@chrisgrim that will fail if the result of find is undefined; needs some fault tolerance

Please or to participate in this conversation.