Lodash 发现 JSON 数组之间的差异

Lodash finding difference between JSON arrays

使用 lodash 寻找差异:

c1Arr 是:

[ { varName: 'city', varValue: 'cccccccc' },
  { varName: 'country', varValue: 'dddddddd' }
 ]

c2Arr 是:

[ { varName: 'abc', varValue: 'aaa' },
  { varName: 'city', varValue: 'cccccccc' },
  { varName: 'country', varValue: 'dddddddd' }
 ]

执行以下代码

    var dArr = _.difference(c2Arr, c1Arr);
    console.log(dArr);

为什么我没有得到结果:

[ { varName: 'abc', varValue: 'aaa' }]

相反,我得到(即 c2Arr)

[ { varName: 'abc', varValue: 'aaa' },
  { varName: 'city', varValue: 'cccccccc' },
  { varName: 'country', varValue: 'dddddddd' }
 ]

您必须提供 comparator 函数,因为元素是对象。

试试这个,

_.differenceWith(c2Arr, c1Arr, _.isEqual);

var c1Arr = [{
  varName: 'city',
  varValue: 'cccccccc'
}, {
  varName: 'country',
  varValue: 'dddddddd'
}]

var c2Arr = [{
  varName: 'abc',
  varValue: 'aaa'
}, {
  varName: 'city',
  varValue: 'cccccccc'
}, {
  varName: 'country',
  varValue: 'dddddddd'
}]

var dArr = _.differenceWith(c2Arr, c1Arr, _.isEqual);
console.log(dArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>