我有一组对象,例如:
[{
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
相同,那么我想从数组中删除该对象。
您可以只使用带有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)
您可以使用一个临时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);
您可以创建一个将objectId
作为其键的对象,如下所示:
var target = {};
for (let item of myArray) {
if (target[item.objectId] === undefined) {
target[item.objectId] = item;
}
}
然后,当您尝试添加到此数组时,只需检查具有特定键的项目是否已存在。