-1

i have a list of countries with id i want to pull the country id of a specific country name

 export const country_list_with_id = [
        {
            id: 1,
            code: "AF",
            name: "Afghanistan"
        },
        {
            id: 2,
            code: "AL",
            name: "Albania"
        },
        {
            id: 3,
            code: "DZ",
            name: "Algeria"
        },
        {
            id: 4,
            code: "DS",
            name: "American Samoa"
        },
    ...

if have country name like

countryname = algeria 

is there a function to help me easily retrieve its country id

getcountryid(countryname){
return id 
}

I Found a solution

   getcountryid(countryname){
   country_list_with_id.map(res=>{
    if(res.name === country name){
       return res.id
        }
       });
      }
jadlmir
  • 465
  • 1
  • 6
  • 16

2 Answers2

3

I think you can do something like that:

country_list_with_id.find(country=> country.name.toLowerCase() === countryname)
benjamin Rampon
  • 1,316
  • 11
  • 18
0

You can create your own function like this, supposing you already saved your data in an Array of Objects :

myResponse = [];

function(country) = {
 var id=0;
 this.myResponse.forEach((res) => {
     if (res.countryname.toLowerCase() === country) {
      id = res.id;
     }
  }
}

Or using find instead :

var countryName = "algeria";
var found = this.myResponse.find((res) => {
  return countryName === res.countryName.toLowerCase();
});
andrea06590
  • 1,259
  • 3
  • 10
  • 22
  • a lile help here please i used . – jadlmir Mar 09 '18 at 08:04
  • getCountryID(countryName) { const countryID = country_list_with_id.forEach(res => { if (res.name.toLowerCase() === countryName) { return res.id; console.log("res.id= ", res.id); } }); console.log("countryID is", countryID); } – jadlmir Mar 09 '18 at 08:04
  • but countryID is alwways undefined how should i return it – jadlmir Mar 09 '18 at 08:04