Actually, I meet with an iterate problem when I compare two arrays of objects.
Array Old:
[{uuid:'a'}, {uuid:'b'}, {uuid:'c'}]
Array New:
[{uuid:'a'}, {uuid:'e'}, {uuid:'f'}]
what I am going to do is calling the api under the below logic:
compare 'new' with 'old' to get the result:
[{name:1, uuid:'e'}, {name:1, uuid:'f'}]
and then call the POST api one by one to add new uuid: 'e' and 'f'
compare 'new' with 'old' to get the result:
[{name:1, uuid:'b'},{name:1, uuid:'c'}]
and then call the Delete api one by one to delete uuid: 'b' and 'c'
I have tried the below code to find the difference, but it seems not correct:(need some help)
const postArr = [];
for (var i = 0; i < this.new.length; i++) {
for (var o = 0; o < this.old.length; o++) {
if (
this.new[i].uuid !==
this.old[o].uuid
) {
postArr.push(this.new[i]);
}
}
}
console.log(postArr);
with filter and mapping u can achive uniques in old array
var a=[{uuid:'a'}, {uuid:'b'}, {uuid:'c'}];
var b=[{uuid:'a'}, {uuid:'e'}, {uuid:'f'}];
var keys = ['uuid'];
console.log(findDifferences(a,b))
function findDifferences(objectA, objectB) {
var result = objectA.filter(function(o1){
return !objectB.some(function(o2){
return o1.uuid === o2.uuid;
});
}).map(function(o){
return keys.reduce(function(newo, name){
newo[name] = o[name];
return newo;
}, {});
});
return result;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments