获取两个对象数组之间的差异 [英] Get the difference between two arrays of objects
本文介绍了获取两个对象数组之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个对象数组,它们之间的区别只在于arrayAfter会添加一个元素:
I've got two arrays of objects, the difference between them is only that arrayAfter will have an element added:
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"}
];
name始终是唯一的!
"name" is always unique!
我怎样才能找出哪一个是已添加的元素?我试过最后使用嵌套for循环,但这似乎过于复杂。
How can I find out which one is the element that has been added? I've tried ending up using nested for loops, but this seems overcomplicated.
我也发现了这个好主意:
I've also found the this nice idea:
var diff = $(arrayAfter).not(arrayBefore ).get();
但是,这似乎不能直接用于对象数组。
However, that does not seem to work on arrays of objects straight ahead.
是否有一些简单的方法可以获得差异?
推荐答案
如果只有名称表示唯一性,您可以这样做:
If only the name indicates uniqueness, you can do:
//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/
这篇关于获取两个对象数组之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文