从阵列深度检查中删除重复的对象

问题描述 投票:1回答:3

我有一组对象,例如:

[{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    } 
  }
},
{
  actionType: 10,
  orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
  productComponentAction:{
    productComponent:{
      offerId: 10002839,
      parentOfferId: 10003058,
      adoptableProdCompId: undefined
    } 
  }
}]

我希望此数组在offerId的基础上是唯一的。如果offerId相同,那么我想从数组中删除该对象。

javascript arrays ecmascript-6 duplicates
3个回答
2
投票

您可以只使用带有reduce的Map,然后从Map中获取值:

const arr = [{
    actionType: 10,
    orderItemId: "3205ae52-ab00-4823-a004-da0cda639065",
    productComponentAction: {
      productComponent: {
        offerId: 10002839,
        parentOfferId: 10003058,
        adoptableProdCompId: undefined
      }
    }
  },
  {
    actionType: 10,
    orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae",
    productComponentAction: {
      productComponent: {
        offerId: 10002839,
        parentOfferId: 10003058,
        adoptableProdCompId: undefined
      }
    }
  }
]

const filtered = Array.from(arr.reduce((a, v) => {
  const id = v.productComponentAction.productComponent.offerId
  if(!a.has(id)) a.set(id, v)
  return a
}, new Map()).values())

console.log(filtered)

2
投票

您可以使用一个临时Map,并以您希望唯一的键为键。它的构造函数接受[key,value]对:

let data = [{actionType: 10, orderItemId: "3205ae52-ab00-4823-a004-da0cda639065", productComponentAction:{productComponent:{ offerId: 10002839, parentOfferId: 10003058,     adoptableProdCompId: undefined } }},{actionType: 10,orderItemId: "3205ae52-ab00-4823-2121-da0cda6390ae", productComponentAction:{ productComponent:{ offerId: 10002839,      parentOfferId: 10003058, adoptableProdCompId: undefined  }  }}];

let uniques = Array.from(new Map(
     data.map(item => [item.productComponentAction.productComponent.offerId, item])
).values());
    
console.log(uniques);

0
投票

您可以创建一个将objectId作为其键的对象,如下所示:

var target = {};
for (let item of myArray) {
    if (target[item.objectId] === undefined) {
        target[item.objectId] = item;
    }
}

然后,当您尝试添加到此数组时,只需检查具有特定键的项目是否已存在。

© www.soinside.com 2019 - 2024. All rights reserved.