仅匹配一个键的两个数组的Lodash差

时间:2018-08-31 06:30:22

标签: javascript arrays lodash

我有一个像这样的数组

var old = [ { id: 1, name: 'Super edit' },
  { id: 2, name: 'new item' },
  { id: 19, name: 'new item' } ]

var new = [ { id: 1, name: 'Super edit' },{ id: 2, name: 'new item' }]

我想得到以上两个与键id不匹配的区别。

预期结果:

[{ id: 19, name: 'new item' }]

我尝试过的是

_.differenceWith(old,new,_.isEqual),但它同时检查idname  我如何获得仅与键id

匹配的数组

2 个答案:

答案 0 :(得分:1)

使用_.differenceBy()id作为iteratee的简写。

注释new是JavaScript中的reserved word,不能用于变量名。

const oldArr = [{ id: 1, name: 'Super edit' },{ id: 2, name: 'new item' },{ id: 19, name: 'new item' }]

const newArr = [ { id: 1, name: 'Super edit' },{ id: 2, name: 'new item' }]

const result = _.differenceBy(oldArr, newArr, 'id')

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

答案 1 :(得分:1)

您可以像往常一样使用_.lodash。

如果您要变异该数组,请使用_.pullAllBy

如果您不想改变数组,请使用_.differenceBy

var old = [{ id: 1, name: 'Super edit' }, { id: 2, name: 'new item' }, { id: 19, name: 'new item' } ]
var current = [{ id: 1, name: 'Super edit' }, { id: 2, name: 'new item' }]

console.log(_.differenceBy(old, current,'id'))  // this will NOT mutate
console.log(old, current)  // Notice no changes to any of the arrays

console.log(_.pullAllBy(old, current,'id'))    // this will
console.log(old, current)  // Notice old array is now changed
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>