我有两个数组-A和B。
A:
name: string;
id: string;
{name: 'Hans', id: 0; name: 'Caleb', id: 1; name: 'Emily', id: 2}
B:
name: string;
collections: [numbers]
{name: 'Pure', collections: [0,2]}
如何过滤ID出现在B的collection
内的数组A的所有对象?
我尝试了以下操作,但只能过滤一个静态ID:
const result = this.a.filter(value => value.id === this.b.collections[???];
答案 0 :(得分:3)
使用includes()
尝试这样:
a = [{ name: 'Hans', id: 0 }, { name: 'Caleb', id: 1 }, { name: 'Emily', id: 2 }]
const result = this.a.filter(value => this.b.collections.includes(value.id));
答案 1 :(得分:1)
如果需要匹配名称。
const result = this.a.filter(value => {
const matchWithName = this.b.find(e => e.name === value.name);
if (matchWithName) {
return matchWithName.collections.includes(value.id);
} else {
return false;
}
});