我正在回傳下面的陣列,并希望根據匹配的字串顯示所有匹配的物件。
回傳陣列: ["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)
uj5u.com熱心網友回復:
實作此目的的一種方法是使用reducewith includes。
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"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/335748.html
標籤:javascript 数组 找
