3 回答

TA贡献1811条经验 获得超4个赞
您可以找到名称(如果名称id是唯一的),并将未知对象作为默认对象。
const
getName = id => (countryList.find(o => o.id === id) || {}).name,
countryList = [{ name: 'Afghanistan', id: 'AF' }, { name: 'Åland Islands', id: 'AX' }, { name: 'Albania', id: 'AL' }, { name: 'Algeria', id: 'DZ' }];
console.log(getName('AL'));
console.log(getName('UK'));

TA贡献1839条经验 获得超15个赞
如果国家/地区ID是唯一的,则出于性能原因,您可以使用array.some。
getCountryName = (countryList, id) => {
name = null;
countryList.some((x, idx) => {
result = false;
if(x.id === id) {
name = x.name;
result = true;
}
return result;
});
return name;
}
用法是
getCountryName(countryList, 'AF')
结果是
'Afghanistan'
添加回答
举报