如何从对象数组中删除所有重复对象? [英] How to remove all dupes from an array of objects?
本文介绍了如何从对象数组中删除所有重复对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// This is a large array of objects, e.g.:
let totalArray = [
{"id":"rec01dTDP9T4ZtHL4","fields":
{"user_id":170180717,"user_name":"abcdefg","event_id":516575,
}]
let uniqueArray = [];
let dupeArray = [];
let itemIndex = 0
totalArray.forEach(x => {
if(!uniqueArray.some(y => JSON.stringify(y.fields.user_id) === JSON.stringify(x.fields.user_id))){
uniqueArray.push(x)
} else(dupeArray.push(x))
})
node.warn(totalArray);
node.warn(uniqueArray);
node.warn(dupeArray);
return msg;
我正在成功地对数组进行重复数据消除以仅生成唯一值。问题是,我需要删除两个重复项,例如:如果有2个具有相同user_id键的对象,我想从数组中删除这两个对象,而不仅仅是一个。
I'm successfully deduping the array to produce only unique values. Problem is, I need to remove both duplicates, e.g.: if there are 2 objects with the same user_id key, I want to remove both of the objects from the array, not just one.
推荐答案
一种选择是遍历数组,并将当前要遍历的对象放在 user_id上
属性。如果该属性已经存在,请将其重新分配为 null
。最后,获取对象的值并删除空值:
One option is to iterate over the array and put the current object being iterated over at a user_id
property on the object. If the property already exists there, reassign it to null
instead. At the end, take the values of the object and remove the null values:
const totalArray = [{
"id": "rec01dTDP9T4ZtHL4",
"fields": {
"user_id": 170180717,
"user_name": "abcdefg",
"event_id": 516575,
}
}, {
"id": "rec01dTDP9T4ZtHL4",
"fields": {
"user_id": 170180717,
"user_name": "abcdefg",
"event_id": 516575,
}
}, {
"id": "unique",
"fields": {
"user_id": 1234,
"user_name": "abcdefg",
"event_id": 516575,
}
}];
const uniques = {};
for (const item of totalArray) {
const prop = item.fields.user_id;
uniques[prop] = uniques.hasOwnProperty(prop)
? null
: item;
}
const output = Object.values(uniques).filter(Boolean);
console.log(output);
这篇关于如何从对象数组中删除所有重复对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文