合并数组中的重复对象

时间:2018-07-15 09:24:02

标签: javascript

我有一个数组,需要将重复的值与数量的总和合并。 什么是有效的算法

var arr = [{
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 1
}, {
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 2
}, {
    item: {
        id: 2,
        name: "Abc"
    },
    amount: 2
},{
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 2
}]

我需要解决方案

[{
    item: {
        id: 1,
        name: "Abc"
    },
    amount: 5
}, {
    item: {
        id: 2,
        name: "Abc"
    },
] amount: 2
}]

2 个答案:

答案 0 :(得分:3)

Object.values()Array.reudce()一起使用以合并对象,然后获取值:

var arr = [{ item: { id: 1, name: "Abc" }, amount: 1 }, { item: { id: 1, name: "Abc" }, amount: 2 }, { item: { id: 2, name: "Abc" }, amount: 2 },{ item: { id: 1, name: "Abc" }, amount: 2 }];

var result = Object.values(arr.reduce((a,curr)=>{

  if(!a[curr.item.id])
    a[curr.item.id] = Object.assign({},curr); // Object.assign() is used so that the original element(object) is not mutated.
   else 
     a[curr.item.id].amount += curr.amount;
    return a;
},{}));

console.log(result);

答案 1 :(得分:0)

使用getResource捕获所有:D

map