简体   繁体   English

通过深层嵌套键映射重复项后获取整个对象数组

[英]Get entire array of objects after mapping duplicates by a deep nested key

I have a huge nested array of objects and I want to filter and remove the duplicates, defined by the deep nested key uniqueId .我有一个巨大的嵌套对象数组,我想过滤和删除由深层嵌套键uniqueId定义的重复项。 With the following mapping I only get the values for the key uniqueId .通过以下映射,我只能获得键uniqueId的值。 But I need the entire array of objects m .但我需要整个对象数组m

JS JS

var medis = [...new Map(m.map( o => [o['drugs'][0]['ingredient'].uniqueId, o['drugs'][0]['ingredient'].uniqueId])).values()];

Questions:问题:

  1. How do I get the filtered array m ?如何获得过滤后的数组m
  2. Is it possible within the mapping to keep only the last duplicate?是否可以在映射中只保留最后一个副本?

Thank you for your hints谢谢你的提示

It's a bit tricky to know exactly what you want because you don't provide sample data, but here's something that might work.由于您不提供示例数据,因此确切地知道您想要什么有点棘手,但这里有一些可能有效的方法。 Instead of reducing the array in place, I'm making a new map n .我没有减少阵列,而是制作了一个新的 map n

 //var medis = [...new Map(m.map( o => [o['drugs'][0]['ingredient'].uniqueId, o['drugs'][0]['ingredient'].uniqueId])).values()]; let m = [ {'drugs':[ {'ingredient': { 'name':'first', 'uniqId':1 }} ]}, {'drugs':[ {'ingredient': { 'name':'second', 'uniqId':2 }} ]}, {'drugs':[ {'ingredient': { 'name':'first-overwritten', 'uniqId':1 }} ]}, ] let n = new Map(); m.map(o=>{n[o['drugs'][0]['ingredient'].uniqId]=o}); console.log(n);

I would rather use a Set to store the unique ids.我宁愿使用Set来存储唯一 ID。 You could use Reduce instead of map to do your filter.您可以使用Reduce而不是 map 来进行过滤。 There you would validate if the set contains the object key in order to add to the accumulator array:在那里您将验证该集合是否包含 object 键以添加到累加器数组:

const uniqueKeys = new Set()

const medis = m.reduce((uniqueArray, o) => {
  const key = o['drugs'][0]['ingredient'].uniqueId
  if(uniqueKeys.has(key)) return uniqueArray
  uniqueKeys.add(key)
  uniqueArray.push(o)
  return uniqueArray
},[])

Note: If you want to store to the array each last object duplicated instead you can use ReduceRight instead.注意:如果您想将每个最后一个 object 重复存储到数组中,您可以使用ReduceRight代替。

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

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