【问题标题】:How to filter array of objects based on other array of objects?如何根据其他对象数组过滤对象数组?
【发布时间】:2020-12-14 01:13:13
【问题描述】:

我有 2 个对象数组:

Array1
Array2

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

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

上述解决方案总是返回空数组。出了什么问题,如何解决?

【问题讨论】:

    标签: javascript arrays ecmascript-6 javascript-objects ecmascript-5


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2013-10-08
      • 2020-10-17
      • 1970-01-01
      • 2019-02-13
      • 2018-12-25
      • 2020-10-01
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多