如何将i18n-iso-countries的JSON转换为带键值的数组?
解决方案:将i18n-iso-countries的国家对象转换为指定数组结构
你可以通过以下两种方式实现需求:
方法一:使用Object.entries()(推荐,ES2017+)
Object.entries()会直接返回原对象的键值对数组,再通过map转换为目标结构:
const countries = { AD: "Andorra", AE: "United Arab Emirates", AF: "Afghanistan", AG: "Antigua and Barbuda" }; const formattedCountries = Object.entries(countries).map(([id, country]) => ({ id, country }));
执行后formattedCountries就是你需要的数组结构:
[ { id: 'AD', country: 'Andorra' }, { id: 'AE', country: 'United Arab Emirates' }, { id: 'AF', country: 'Afghanistan' }, { id: 'AG', country: 'Antigua and Barbuda' } ]
方法二:使用Object.keys()(兼容旧环境)
如果需要支持不支持Object.entries()的旧环境,可以先获取所有键的数组,再遍历生成目标对象:
const formattedCountries = Object.keys(countries).map(id => ({ id, country: countries[id] }));
内容的提问来源于stack exchange,提问作者Sergio
相关产品推荐
相关产品推荐

