You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:05:22