首页 > 解决方案 > 如果数组中的所有字符串都匹配,则在 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)

标签: javascriptarraysfind

解决方案


实现此目的的一种方法是使用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"]


推荐阅读