所以我有一个国家名称数组缩写试图获取并显示一个对象中的完整国家名称。
const countries = [
{
name:'Argentina',
border:["NGA", "PAK","CHN"],
},
{
name:'China',
border:["ARG", "PAK"],
},
{
name:'Nigeria',
border:['PAK', 'CHN'],
},
{
name:'Pakistan',
border:['NGA', 'ARG'],
},
]
所以如果我访问数组的第一个索引,名称是阿根廷和 nga,pak 和 chn 的边界
const country = countries.find((con) => con.name === "Argentina");
console.log(country.border);
});
所以我只在控制台中看到 Abbr 值,就像预期的那样
[NGA, PAK, CHN]
但我真的想要这样的东西
[Nigeria, Pakistan, China]
那么,我如何使用提供的对象将国家的 fullName 记录到控制台,因为已经想到并想到了一种方法来做到这一点,但我只是没有得到这个想法data-URL-link

您可以首先创建一个dict
作为
fetch("https://restcountries.eu/rest/v2/all")
.then((res) => res.json())
.then((data) => {
const dict = data.reduce((acc, curr) => {
acc[curr.alpha3Code] = curr.name;
return acc;
}, {});
console.log(dict);
});
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
const dict = {
NGA: "Nigeria",
PAK: "Pakistan",
CHN: "China",
ARG: "Argentina",
};
const countries = [
{
name: "Argentina",
border: ["NGA", "PAK", "CHN"],
},
{
name: "China",
border: ["ARG", "PAK"],
},
{
name: "Nigeria",
border: ["PAK", "CHN"],
},
{
name: "Pakistan",
border: ["NGA", "ARG"],
},
];
const result = countries.map((o) => dict[o.border[0]]);
console.log(result);
您可以通过将 abbrs 更改为全名的函数来映射结果。
const countries = [
{
name:'Argentina',
border:["NGA", "PAK","CHN"],
},
{
name:'China',
border:["ARG", "PAK"],
},
{
name:'Nigeria',
border:['PAK', 'CHN'],
},
{
name:'Pakistan',
border:['NGA', 'ARG'],
},
]
const abrRefrence = {
CHN: "China",
PAK: "Pakistan",
NGA: "Nigeria",
ARG: "Argentina",
}
const abrToFull = abr => abrRefrence[abr];
const country = countries.find(con => con.name === "Argentina");
console.log(country.border.map(abrToFull));
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(59条)