通过其他对象数组过滤对象数组

时间:2020-09-10 17:22:34

标签: javascript

我有下一个数组:

let arr1 = [{id: 1, type: 'a', size: 12},{id: 2, type: 'b', size: 13},{id: 3, type: 'c', size: 14}];
let arr2 = [{id: 1, type: 'a'},{id: 2, type: 'b'}];

我需要的是用具有相同ID的arr2过滤arr1。 预期结果:

[{id: 1, type: 'a', size: 12},{id: 2, type: 'b', size: 13}];

1 个答案:

答案 0 :(得分:1)

您可以使用includes

let arr1 = [
  { id: 1, type: "a", size: 12 },
  { id: 2, type: "b", size: 13 },
  { id: 3, type: "c", size: 14 },
]
let arr2 = [
  { id: 1, type: "a" },
  { id: 2, type: "b" },
]

const res = arr1.filter((el1) => arr2.map((el2) => el2.id).includes(el1.id))

console.log(res)