簡體   English   中英

根據屬性值刪除對象數組中的重復項

[英]Removing Duplicates in Array of Objects based on Property Values

我有一組對象,我試圖根據某些屬性(第一個和最后一個)查找重復項。 我的邏輯似乎不正常,這就是我嘗試過的。

我的最終結果應該類似於:

[
  {first:"John", last: "Smith", id:"1234", dupes: [555,666]},
  {first:"John", last: "Jones", id:"333", dupes: []}
];

 let arrayOfObjects = [ {first:"John", last: "Smith", id:"1234", dupes: []}, {first:"John", last: "Smith", id:"555", dupes: []}, {first:"John", last: "Jones", id:"333", dupes: []}, {first:"John", last: "Smith", id:"666", dupes: []} ]; arrayOfObjects.forEach(record => { arrayOfObjects.forEach(rec => { if(record.first == rec.first && record.last == rec.last && record.id !== rec.id){ console.log("match found for: " + JSON.stringify(record) + " and: " + JSON.stringify(rec)); record.dupes.push(rec.id); //probably need to remove something here } }); }); console.log(JSON.stringify(arrayOfObjects));

首先,請不要在不執行映射操作時使用.map() 我用.forEach代替了.map的用法,因為后者在這種情況下更合適。

其次,您的評論//probably need to remove something here是正確的 - 您必須刪除一個項目。 也就是說,您必須刪除剛剛找到的重復項rec 為此,您可以使用需要刪除索引的Array#splice 您可以輕松獲取索引作為.forEach()回調的第二個參數

 let arrayOfObjects = [ {first:"John", last: "Smith", id:"1234", dupes: []}, {first:"John", last: "Smith", id:"555", dupes: []}, {first:"John", last: "Jones", id:"333", dupes: []}, {first:"John", last: "Smith", id:"666", dupes: []} ]; arrayOfObjects.forEach(record => { arrayOfObjects.forEach((rec, index) => { // get index ------------------^^^^^-->------------------>--------------v if(record.first == rec.first && // | record.last == rec.last && // | record.id !== rec.id){ // | record.dupes.push(rec.id); // | arrayOfObjects.splice(index, 1) //<--- remove using the index --< } }); }); console.log(JSON.stringify(arrayOfObjects));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM