我有两个对象数组,它们之间的区别仅在于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/
关于javascript - 获取两个对象数组之间的差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32378995/