我有一个来自后端的对象数组,如下所示。
let input = [
{month: "Dec", count: "45"},
{month: "Mar", count: "12"},
{month: "June", count: "5"}
]
下面的变量
dropdownValues
是用户在前端下拉列表中选择的变量。
let dropdownValues = [
{key: 'Mar'},
{key: 'June'}
]
因此考虑到用户在下拉列表中选择了
Mar
和 June
,我们希望 input
变量仅选择这些键并将其与 month
的 input
属性进行比较,并删除其他对象。
所以基于
dropdownValues
的最终输出应该是这样的
output = [
{month: "Mar", count: "12"},
{month: "June", count: "5"}
]
为了达到这个结果,我尝试执行以下操作,但它没有过滤掉
Dec
月对象。
let output = input?.filter((el) => {
return dropdownValues.some((f) => {
return f.key === el.month;
});
});
有人可以让我知道我哪里出了问题吗?
您的方法几乎是正确的,但问题是由于使用了可选链接(输入?),如果定义了输入,则在这种情况下不需要。另外,你的过滤逻辑是正确的;它应该根据 dropdownValues 数组过滤输入数组。
let input = [
{month: "Dec", count: "45"},
{month: "Mar", count: "12"},
{month: "June", count: "5"}
];
let dropdownValues = [
{key: 'Mar'},
{key: 'June'}
];
let output = input.filter(el => {
return dropdownValues.some(f => f.key === el.month);
});
console.log(output);