Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从reactjs中的国家名称获取国家id_Javascript_Reactjs_Data Structures - Fatal编程技术网

Javascript 从reactjs中的国家名称获取国家id

Javascript 从reactjs中的国家名称获取国家id,javascript,reactjs,data-structures,Javascript,Reactjs,Data Structures,我有一个id为的国家列表我想提取特定国家名称的国家id export const country_list_with_id = [ { id: 1, code: "AF", name: "Afghanistan" }, { id: 2, code: "AL", name: "Albania"

我有一个id为的国家列表我想提取特定国家名称的国家id

 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"
        },
    ...
如果你有国名像

countryname = algeria 
是否有一个函数可以帮助我轻松检索其国家id

getcountryid(countryname){
return id 
}
我找到了解决办法

   getcountryid(countryname){
   country_list_with_id.map(res=>{
    if(res.name === country name){
       return res.id
        }
       });
      }

我想你可以这样做:

country_list_with_id.find(country=> country.name.toLowerCase() === countryname)

假设您已经将数据保存在一个对象数组中,您可以这样创建自己的函数:

myResponse = [];

function(country) = {
 var id=0;
 this.myResponse.forEach((res) => {
     if (res.countryname.toLowerCase() === country) {
      id = res.id;
     }
  }
}
或者改用“查找”:

var countryName = "algeria";
var found = this.myResponse.find((res) => {
  return countryName === res.countryName.toLowerCase();
});

这里有一个我使用过的lile帮助。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是”,countryID);}但是countryID总是未定义,我该如何返回它