简体   繁体   English

如何通过键值对对对象数组进行重复数据删除?

[英]How to dedupe an array of objects by a key value pair?

// 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) === JSON.stringify(x))){
    uniqueArray.push(x)
  } else(dupeArray.push(x))
})

node.warn(totalArray);
node.warn(uniqueArray);
node.warn(dupeArray);

return msg;

I need my code to identify duplicates in the array by a key value of user_id within the objects in the array.我需要我的代码通过数组中对象中user_id的键值来识别数组中的重复项。 Right now, my code works to identify identical objects in the array, but I need it to identify dupes based on a key value inside the objects instead.现在,我的代码可以识别数组中的相同对象,但我需要它来根据对象内部的键值来识别欺骗。 How do I do this?我该怎么做呢? I am struggling to figure out how to path the for each loop to identify the dupe based on the key value instead of the entire object.我正在努力弄清楚如何根据键值而不是整个 object 来确定每个循环的路径以识别欺骗。

Right now, my code works to identify identical objects in the array, but I need it to identify dupes based on a key value inside the objects instead.现在,我的代码可以识别数组中的相同对象,但我需要它来根据对象内部的键值来识别欺骗。 How do I do this?我该怎么做呢?

Don't compare the JSON representation of the whole objects then, but only their user_id property specifically.然后不要比较整个对象的 JSON 表示,而只比较它们的user_id属性。

totalArray.forEach(x => {
  if(!uniqueArray.some(y => y.fields.user_id === x.fields.user_id)){
    uniqueArray.push(x)
  } else(dupeArray.push(x))
})

You could take a Set and push to either uniques or duplicates.您可以使用Set并推送到唯一或重复项。

 var array = [ { id: 1, data: 0 }, { id: 2, data: 1 }, { id: 2, data: 2 }, { id: 3, data: 3 }, { id: 3, data: 4 }, { id: 3, data: 5 }, ], uniques = [], duplicates = []; array.forEach( (s => o => s.has(o.id)? duplicates.push(o): (s.add(o.id), uniques.push(o))) (new Set) ); console.log(uniques); console.log(duplicates);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

One way is to keep a list of ids you found so far and act accordingly:一种方法是保留到目前为止找到的 id 列表并采取相应措施:

 totalArray = [ { id: 1, val: 10 }, { id: 2, val: 20 }, { id: 3, val: 30 }, { id: 2, val: 15 }, { id: 1, val: 50 } ] const uniqueArray = [] const dupeArray = [] const ids = {} totalArray.forEach( x => { if (ids[x.id]) { dupeArray.push(x) } else { uniqueArray.push(x) ids[x.id] = true } }) for (const obj of uniqueArray) console.log("unique:",JSON.stringify(obj)) for (const obj of dupeArray) console.log("dupes: ",JSON.stringify(obj))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM