针对另一个对象数组过滤对象数组?

时间:2020-10-01 04:27:47

标签: javascript arrays

customerProducts: [
  {
    name: "foo",
    id: 123
  },
  {
    name: "test",
    id: 44
  }
]

otherProducts: [
  {
    name: "other",
    id: 44
  },
  {
    name: "test",
    id: 21
  }
]

我想遍历customerProducts,它是一个对象数组。我想过滤customerProducts的ID,该ID具有另一个对象数组otherProducts的ID。因此,例如,在这种情况下,我希望返回的结果是:

  {
    name: "test",
    id: 44
  }

因为otherProducts的{​​{1}}为44。

我当时想通过id进行映射,然后返回一个ID数组,然后在其上运行otherProducts,但这似乎是很长的路要走。

3 个答案:

答案 0 :(得分:3)

创建值的索引Set进行过滤({{1}中的id),然后根据该集合过滤otherProducts

customerProducts

答案 1 :(得分:0)

customerProducts otherProducts声明为JS数组变量,并使用JS Array filter find函数

let customerProducts = [
  {
    name: "foo",
    id: 123
  },
  {
    name: "test",
    id: 44
  }
]

let otherProducts = [
  {
    name: "other",
    id: 44
  },
  {
    name: "test",
    id: 21
  }
];

let filtered = customerProducts.filter( el => otherProducts.find( e => e.id == el.id) )

console.log(filtered);

答案 2 :(得分:0)

这可以通过使用数组方法filtersome来完成。

customerProducts.filter((x)=> otherProducts.some(y=> y.id === x.id));

说明: filter方法将调用otherProducts数组中的每个元素,并检查idcustomerProduct的{​​{1}}是否存在至少一个元素。