按数组过滤对象数组
Posted
技术标签:
【中文标题】按数组过滤对象数组【英文标题】:Filter array of objects by array 【发布时间】:2021-08-27 10:35:29 【问题描述】:如何用另一个数组值过滤下面的数组?
const GuideTabs = [
id: 0, label: 'Highlights', analyticsCategory: 'Highlights' ,
id: 1, label: 'Labor & Employment', analyticsCategory: 'Labor & Employment' ,
id: 2, label: 'Culture', analyticsCategory: 'Culture' ,
id: 3, label: 'Holidays', analyticsCategory: 'Holidays' ,
]
我想用下面的数组过滤这个数组,只返回现有的数据
const gtabs = ['Culture, Holidays']
const arr = GuideTabs.filter(function(item)
return gtabs.indexOf(item.id) === -1
)
但它总是返回 GuideTabs 中的所有 4 个数组项,但它应该返回 2,3 个项 GuideTabs 数组
const GuideTabs = [
id: 0, label: 'Highlights', analyticsCategory: 'Highlights' ,
id: 1, label: 'Labor & Employment', analyticsCategory: 'Labor & Employment' ,
id: 2, label: 'Culture', analyticsCategory: 'Culture' ,
id: 3, label: 'Holidays', analyticsCategory: 'Holidays' ,
]
const gtabs = ['Culture, Holidays']
const arr = GuideTabs.filter(function(item)
return gtabs.indexOf(item.id) === -1
)
console.log(arr)
【问题讨论】:
const gtabs = ['Culture, Holidays']
这是一个包含一个元素的数组。我想这应该是const gtabs = ['Culture', 'Holidays']
return gtabs.indexOf(item.label) != -1
?
【参考方案1】:
你需要使用
gtabs.includes(obj.label))
因为您要与包含字符串的gTabs
进行比较,即"Culture", "Holidays"
const GuideTabs = [
id: 0, label: "Highlights", analyticsCategory: "Highlights" ,
id: 1,
label: "Labor & Employment",
analyticsCategory: "Labor & Employment",
,
id: 2, label: "Culture", analyticsCategory: "Culture" ,
id: 3, label: "Holidays", analyticsCategory: "Holidays" ,
];
const gtabs = ["Culture", "Holidays"];
const result = GuideTabs.filter((obj) => gtabs.includes(obj.label));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
【讨论】:
【参考方案2】:您也可以使用some
和filter
。
const result = GuideTabs.filter((tab) => gtabs.some((guideTab) => guideTab === tab.label));
【讨论】:
以上是关于按数组过滤对象数组的主要内容,如果未能解决你的问题,请参考以下文章