如何基于其他对象数组过滤对象数组?

问题描述

我有2个对象数组:

Array1
Array2

我试图通过仅获取productId与array2项目productId相同的项目来过滤Array1

const filteredArray = Array1.filter(item =>
  Array2.includes(item.productId),)

以上解决方案始终返回空数组。有什么问题,如何解决

解决方法

您需要尊重array2的属性,因为没有对象等于另一个原始类型,例如字符串或数字。

filteredArray = Array1.filter(one => Array2.some(two => one.productId === two.productId));