具有部分相似对象的两个数组之间的差异(基于自定义属性),即 a-b

Difference (upon custom attributes) between two arrays having partial similar objects i.e a-b

如何找到具有部分相似对象的两个 JavaScript 数组之间的差异?

差异 = A 减去 B

const firstList = [{ key: "aa", name:"a" }, { key: "bb", name:"b" }, { key: "cc", name:"c" }];
const secondList = [{ key: "dd", id: 1 }, { key: "cc", id: 2 }];

我想要 const diff = firstList - secondList;

在这种情况下 diff 需要持有 [ { key: 'aa', name: 'a' }, { key: 'bb', name: 'b' } ]

const firstList = [{ key: "aa", name:"a" }, { key: "bb", name:"b" }, { key: "cc", name:"c" }];
const secondList = [{ key: "dd", id: 1 }, { key: "cc", id: 2 }];

const diff = firstList.filter((first) => {
  return !secondList.some((second) => second.key === first.key);
});

diff; // [ { key: 'aa', name: 'a' }, { key: 'bb', name: 'b' } ]

您可以为第二个数组取 Set 并过滤第一个数组以排除与第二个数组具有相同 key 的元素。

const
    firstList = [{ key: "aa" }, { key: "bb" }, { key: "cc" }],
    secondList = [{ key: "dd" }, { key: "cc" }],
    keys = new Set(secondList.map(({ key }) => key)),
    result = firstList.filter(({ key }) => !keys.has(key));

console.log(result);