如果所有字符串在数组中匹配,那么在Javascript中显示匹配的对象



我得到下面的数组,并希望根据匹配的字符串显示所有匹配的对象。

返回数组:["USA", "FRA", "GBR"]

原始数组:

export const COUNTRY_CODES = [
{
country: "United States of America",
code: "USA",
},
{
country: "Albania",
code: "ALB",
},
{
country: "Algeria",
code: "DZA",
},
{
country: "France",
code: "FRA",
},
....
]

我想要的输出是显示匹配的国家:

["United States of America", "France"]

JS:

const flatArr = ["USA", "FRA", "GBR"]
COUNTRY_CODES.find((v) => flatArr === v.country)

实现这一目标的一种方法是使用reduceincludes

const COUNTRY_CODES = [
{
country: "United States of America",
code: "USA",
},
{
country: "Albania",
code: "ALB",
},
{
country: "Algeria",
code: "DZA",
},
{
country: "France",
code: "FRA",
},
];
const flatArr = ["USA", "FRA", "GBR"];
const matchedCountries = COUNTRY_CODES.reduce((matched, countryCode) => {
if (flatArr.includes(countryCode.code)) {
matched.push(countryCode.country);
}
return matched;
}, []);
console.log(matchedCountries); // ["United States of America", "France"]

相关内容

  • 没有找到相关文章

最新更新