使用npm包countries-list获取所有国家列表遇问题求助
解决方案:遍历
countries-list的国家数据 countries-list导出的countries是键值对对象(键为国家代码,值为国家信息),而非数组,所以无法用数组的索引遍历或forEach直接调用。以下是几种可行的遍历方式:
方式1:通过Object.values()直接获取国家对象数组
直接提取所有国家信息的数组,再用数组方法遍历:
import { countries } from 'countries-list'; // 获取所有国家信息的数组 const allCountries = Object.values(countries); // 遍历数组获取每个国家的信息 allCountries.forEach(country => { console.log(`国家名称:${country.name}`); console.log(`首都:${country.capital}`); console.log(`所属大洲:${country.continent}`); });
方式2:通过Object.keys()获取国家代码再遍历
如果需要同时获取国家代码和对应信息:
import { countries } from 'countries-list'; // 获取所有国家代码的数组 const countryCodes = Object.keys(countries); countryCodes.forEach(code => { const country = countries[code]; console.log(`国家代码:${code}`); console.log(`国家名称:${country.name}`); });
方式3:使用for...in循环
传统的对象遍历方式,注意添加属性校验避免遍历原型链:
import { countries } from 'countries-list'; for (const code in countries) { // 确保是对象自身的属性,排除原型链上的属性 if (Object.hasOwn(countries, code)) { const country = countries[code]; console.log(`${code} - ${country.name}:${country.capital}`); } }
推荐替代npm包
以下是功能更完善、易用性更高的同类包:
- i18n-iso-countries:严格遵循ISO 3166标准,支持多语言本地化,可快速获取不同语言的国家名称,API设计灵活,适合多语言项目。
- country-data:包含国家基础信息、货币、语言、时区等多维度数据,结构清晰,同时支持对象键值对和数组两种访问形式。
- world-countries:提供更丰富的地理数据(如经纬度、边界坐标等),所有国家数据以数组形式存储,无需额外处理即可直接用数组方法遍历,适合需要地理信息的场景。
内容的提问来源于stack exchange,提问作者user1960836
相关产品推荐
相关产品推荐

