var A = [{
id: 1,
name: "Apple"
}, {
id: 2,
name: "Orange"
}, {
id: 3,
name: "Mango"
}];
var B = [{
id: 1,
name: "Apple"
}, {
id: 3,
name: "Mango"
}, {
id: 4,
name: "Berry"
}];
我想要添加对象; [{ id: 4, name: "Berry" }
删除对象; [{ id: 2, name: "Orange" }]
请告诉我最简单的方法。我尝试使用数组差异,但是代码太复杂了。感谢。
答案 0 :(得分:-1)
要进行对象比较,我现在能想到的最简单的方法是' stringify'它
var A = [{ id: 1, name: "Apple" }, { id: 2, name: "Orange" }, { id: 3, name: "Mango"}];
var B = [{ id: 1, name: "Apple" }, { id: 3, name: "Mango" }, { id: 4, name: "Berry" }];
var strA = A.map(function(item){return JSON.stringify(item);})
var strB = B.map(function(item){return JSON.stringify(item);})
var addedObjs = strB
.filter((item) => strA.indexOf(item) < 0)
.map((item) => JSON.parse(item));
var removedObjs = strA
.filter((item) => strB.indexOf(item) < 0)
.map((item) => JSON.parse(item));
console.log(addedObjs);
console.log(removedObjs);
&#13;