获取两个对象数组之间的差异

我有两个对象数组,它们之间的区别只在于arrayAfter会添加一个元素:

var arrayBefore = [ {"name":"Alan","height":"171","weight":"66"}, {"name":"Ben","height":"182","weight":"90"} ]; var arrayAfter= [ {"name":"Alan","height":"171","weight":"66"}, {"name":"Ben","height":"182","weight":"90"}, {"name":"Chris","height":"163","weight":"71"} ]; 

“名字”永远是独一无二的!

如何找出哪一个是已添加的元素? 我试过最后使用嵌套for循环,但这似乎过于复杂。

我也发现了这个好主意:

 var diff = $(arrayAfter).not(arrayBefore ).get(); 

但是,这似乎不能直接用于对象数组。

是否有一些简单的方法来获得差异?

如果只有名称表示唯一性,您可以:

 //Get a list of all the names in the before array var beforeNames = arrayBefore.map(function(person) { return person.name }); //Filter the after array to only contain names not contained in the before array var uniqueObjects = arrayAfter.filter(function(person) { return beforeNames.indexOf(person.name) === -1; }); console.log(uniqueObjects); //[{"name":"Chris","height":"163","weight":"71"}] 

演示: http : //jsfiddle.net/tehgc8L5/

对于通用方法,您可以将Array.prototype.filter()Array.prototype.reduce()组合在一起,迭代对象键:

 arrayAfter.filter(function(after) { return !arrayBefore.reduce(function(found, before) { if (!found) { found = true; for (key in before) { if (before.hasOwnProperty(key)) { found = found && (before[key] === after[key]); } } } return found; }, false); }); //[{name: "Chris", height: "163", weight: "71"}] 

您可以使用Array.prototype.filter并过滤掉前一个数组中的这些元素。

 var differences = arrayAfter.filter(function(el) { return arrayBefore.indexOf(el) === -1; }); 

我相信jQuery没有什么可以直接解决你的问题。 你的问题是比较对象是否相等。

我假设这个名字是独一无二的。 如果没有,对于此方法,您将需要一个唯一的数据标识符。 如果你绝对没有,那么你可以连接所有数据来得到一个。

 // first make a map of objects in before var before = {}; arrayBefore.forEach(function(o){ before[o.name] = o; }); // now we get the elements of after that do not exist in our hashmap var result = arrayAfter.filter(function(o){ return !(o.name in before); }); 

显然,您可以将其包含在一般function中。