过滤ID在数组B中出现的数组A的所有对象

时间:2019-09-18 13:28:31

标签: angular typescript

我有两个数组-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[???];

2 个答案:

答案 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));

Working Demo

答案 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;
  }
});