Javascript 从reactjs中的国家名称获取国家id
我有一个id为的国家列表我想提取特定国家名称的国家idJavascript 从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"
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总是未定义,我该如何返回它