如何使用lodash返回两个数组对象之间存在差异的对象



例如

let array1 = [
{ 'id': 1010, 'name': 'grapes' }, 
{ 'id': 2020, 'name': 'blueberry' },
{ 'id': 3030, 'name': 'banana' }
]
let array2 = [
{ 'id': 1010, 'name': 'apple' }, 
{ 'id': 2020, 'name': 'blueberry' }, 
{ 'id': 4040, 'name': 'banana' },
{'id' : 5050, name 'jackfruit'}
]

输出应该是

let result = [
{ 'id': 1010, 'name': 'grapes' },
{ 'id': 3030, 'name': 'banana' },
{ 'id': 4040, 'name': 'banana' },
{ 'id' : 5050, name 'jackfruit'}
]

这里需要获得一个具有不常见对象数据的数组条目{ 'id': 2020, 'name': 'blueberry' }被删除,因为id和名称在两个阵列中都是通用的

这些示例使用原始问题的数据集,但逻辑仍然代表更新后的问题。

根据你想要的结果,你可以得到这样的数组之间的差异:

const result = _.differenceWith(array1, array2, _.isEqual);

这将输出

{ id: 1010, name: "grapes" }

如果你想要对称的差异,你也可以连接相反的:

const result = _.differenceWith(array1, array2, _.isEqual).concat(_.differenceWith(array2, array1, _.isEqual));

这会给你

{ id: 1010, name: "grapes" }
{ id: 1010, name: "apple" }
{ id: 3030, name: "banana" }

你在问题中引用的结果略有不同,既不是差异也不是对称差异,如果你只想为每个ID得到一个结果,你需要删除任何对象的第二个出现,该对象具有已经存在的ID密钥,如下所示:

result = result.filter((elm, i) => !result.find((elm2, j) => elm.id === elm2.id && i > j) );

这会给你

{ id: 1010, name: "grapes" }
{ id: 3030, name: "banana" }

如果你想自己滚动。

下面的代码找到并集,根据相关属性对其进行排序,然后遍历它。如果一个键与前一个键相同,则会发现重复项,并删除这两个元素。

function except(a,b) {
const union = [...a, ...b]
union.sort(({id: id1}, {id: id2}) => id1 - id2)
const except = []
let previous = null
for(const el of union) {
if(el.id === previous) {
except.pop()
continue;
}
except.push(el)
previous = el.id
}
return except
}
let arr1 = [
{ 'id': 1010, 'name': 'grapes' }, 
{ 'id': 2020, 'name': 'blueberry' },
{ 'id': 3030, 'name': 'banana' }
]
let arr2 = [
{ 'id': 0000, 'name': 'apple' }, 
{ 'id': 2020, 'name': 'blueberry' }, 
{ 'id': 4040, 'name': 'banana' },
{'id' : 5050, name: 'jackfruit'}
]
console.log(except(arr1, arr2))

最新更新