gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:22:50 24 4
gpt4 key购买 nike

我有两个对象数组,它们之间的区别只是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com