[英]How to compare two arrays of objects to find the differences
實際上,當我比較兩個對象的 arrays 時,我遇到了一個迭代問題。
舊數組:
[{uuid:'a'}, {uuid:'b'}, {uuid:'c'}]
陣列新:
[{uuid:'a'}, {uuid:'e'}, {uuid:'f'}]
我要做的是在以下邏輯下調用 api:
比較 'new' 和 'old' 得到結果:
[{name:1, uuid:'e'}, {name:1, uuid:'f'}]
然后一一調用POST api 添加新的uuid: 'e' and 'f'
比較 'new' 和 'old' 得到結果:
[{name:1, uuid:'b'},{name:1, uuid:'c'}]
然后調用Delete api一一刪除uuid: 'b' and 'c'
我試過下面的代碼來找出不同之處,但它似乎不正確:(需要一些幫助)
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);
使用過濾器和映射,您可以在舊數組中獲得唯一性
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; }
試試這個:
function difference(checkingArray, baseArray) {
let diff = [];
let found = 0;
for (let j = 0; j<checkingArray.length; j++) {
found = 0;
for (let i = 0; i<baseArray.length; i++) {
if (baseArray[i].uuid == checkingArray[j].uuid) {
found = 1;
break;
}
}
if (found == 0) {
for (let k = 0; k<diff.length; k++) {
if (diff[k].uuid == checkingArray[j].uuid) {
found = 1;
break;
}
}
if (found == 0) {
diff.push(checkingArray[j]);
}
}
}
return diff;
}
let old = [{uuid:'a'}, {uuid:'b'}, {uuid:'c'}];
let recent = [{uuid:'a'}, {uuid:'e'}, {uuid:'f'}];
let onlyOnNewArray = difference(recent, old); // returns elements only in recent array not in old array
let onlyOnOldArray = difference(old, recent); // returns elements only in old array not in recent array
console.log("only on old array", onlyOnOldArray);
console.log("only on recent array", onlyOnNewArray);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.