javascript 如何根据另一个数组的匹配键值对返回一个数组?

bnlyeluc  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(186)

我有以下两个数组:

const raceOptions = [
    {
        "label": "race_option_american_indian_alaska_native",
        "value": "American Indian/Alaska Native"
    },
    {
        "label": "race_option_asian",
        "value": "Asian"
    },
    {
        "label": "race_option_black_african_american",
        "value": "Black/African American"
    },
    {
        "label": "race_option_native_hawaiian_pacific_islander",
        "value": "Native Hawaiian or Other Pacific Islander"
    },
    {
        "label": "race_option_white",
        "value": "White"
    },
    {
        "label": "prefer_not_to_say",
        "value": ""
    }
]

const selectedRace = [
    "American Indian/Alaska Native",
    "Native Hawaiian or Other Pacific Islander",
    "Black/African American"
]

如何合并/过滤这些数组以输出一个新数组,如下所示?

const filteredArray = [
  'race_option_american_indian_alaska_native',
  'race_option_native_hawaiian_pacific_islander',
  'race_option_black_african_american'
]
nkkqxpd9

nkkqxpd91#

使用Array对象的.forEach()方法,可以迭代raceOptions数组中的元素。在它的回调函数中,您需要将当前元素的.value属性与第二个数组selectedRace中的所有元素进行比较。
这可以通过数组的.find()方法来完成,该方法将根据搜索查询返回元素的。过滤后的元素最终需要被推入新数组filteredArray

const raceOptions = [{
        "label": "race_option_american_indian_alaska_native",
        "value": "American Indian/Alaska Native"
    },
    {
        "label": "race_option_asian",
        "value": "Asian"
    },
    {
        "label": "race_option_black_african_american",
        "value": "Black/African American"
    },
    {
        "label": "race_option_native_hawaiian_pacific_islander",
        "value": "Native Hawaiian or Other Pacific Islander"
    },
    {
        "label": "race_option_white",
        "value": "White"
    },
    {
        "label": "prefer_not_to_say",
        "value": ""
    }
]

const selectedRace = [
    "American Indian/Alaska Native",
    "Native Hawaiian or Other Pacific Islander",
    "Black/African American"
]
let filteredArray = [];
let result;
selectedRace.forEach(element => {
    if (result = raceOptions.find(element2 => element2.value == element)) {
        filteredArray.push(result.label)
    }
});
console.log(filteredArray);

相关问题