2个对象数组之间的区别

2 arrays of object between difference

我想得到第一个数组和第二个数组之间的区别。结果;

var arr1 = [{name: "Yesügey", lastName: "Yeşil", phone: "+90 333 9695395"},
{name: "Firdest", lastName: "Firdevis", phone: "+90 333 4234638"},
{name: "Pehlivan", lastName: "Pehlül", phone: "+90 333 9114821"},
{name: "Urbeyi", lastName: "Usberk", phone: "+90 333 1617245"},
{name: "Kâmile", lastName: "Kâşife", phone: "+90 333 6784334"},
{name: "Akdoruk", lastName: "Akdöl", phone: "+90 333 4687455"}]

var arr2 = [{name: "Yesügey", lastName: "Yeşil", phone: "+90 333 9695395"},
{name: "Firdest", lastName: "Firdevis", phone: "+90 333 4234638"},
{name: "Pehlivan", lastName: "Pehlül", phone: "+90 333 9114821"},
{name: "Urbeyi", lastName: "Usberk", phone: "+90 333 1617245"}]

arr1-arr2

结果:

var result = [{name: "Kâmile", lastName: "Kâşife", phone: "+90 333 6784334"},
{name: "Akdoruk", lastName: "Akdöl", phone: "+90 333 4687455"}]

我想得到它。

Underscore 中的

_.difference 没有成功。我怎样才能遵循一种方法?

如果您想找出两个对象之间的差异,您可以尝试使用 _.filter 和 _.findWhere 函数:

var array1 = [{a: 1},{b: 2}];
var array2 = [{a: 1}];

_.filter(array1, function(obj){ return !_.findWhere(array2, obj); });

不使用 _。但是

var arr1 = [{name: "Yesügey", lastName: "Yeşil", phone: "+90 333 9695395"},{name: "Firdest", lastName: "Firdevis", phone: "+90 333 4234638"},{name: "Pehlivan", lastName: "Pehlül", phone: "+90 333 9114821"},{name: "Urbeyi", lastName: "Usberk", phone: "+90 333 1617245"},{name: "Kâmile", lastName: "Kâşife", phone: "+90 333 6784334"},{name: "Akdoruk", lastName: "Akdöl", phone: "+90 333 4687455"}]

var arr2 = [{name: "Yesügey", lastName: "Yeşil", phone: "+90 333 9695395"},{name: "Firdest", lastName: "Firdevis", phone: "+90 333 4234638"},{name: "Pehlivan", lastName: "Pehlül", phone: "+90 333 9114821"},{name: "Urbeyi", lastName: "Usberk", phone: "+90 333 1617245"}]


function compare(otherArray){
  return function(current){
    return otherArray.filter(function(other){
      return other.name == current.name && other.lastName == 
current.lastName && other.phone == current.phone
    }).length == 0;
  }
}

var onlyInFirst = arr1.filter(compare(arr2));
var onlyInSecond = arr2.filter(compare(arr1));

result = onlyInFirst.concat(onlyInSecond);

console.log(result);

这将适用于您的特定场景。 如果您需要将它用于具有不同类别的其他数组,则需要更改 "return other.name == current.name" 行以包含新的数组对象。 示例

var arr1 = [{key1="value",key2="value"}]
var arr2 = [{key1="different value",key2 = "different value="}]

return 行会说。

return current.key1 == other.key1 && current.key2 = other.key2

原始答案。