我有一个对象数组,我试图根据某些属性(第一个和最后一个)查找重复项。我的逻辑似乎有问题,这是我尝试过的。
我的最终结果应该类似于:
[
{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));
最佳答案
首先,请don't use .map()
when not performing a mapping operation 。我已将 .map
的用法替换为 .forEach
,因为后者在这种情况下更合适。
其次,您的评论//可能需要在此处删除某些内容
是正确的 - 您确实必须删除一个项目。也就是说,您必须删除刚刚找到的重复项 rec
。为此,您可以使用 Array#splice
这需要删除索引。您可以轻松获取索引as the second parameter of the .forEach()
callback
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));
关于javascript - 根据属性值删除对象数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741865/