-1

This is array I need to merge these object if values are equal

var arr = [
  {item: {id: 1, name: "sample"}, amount: 1}, 
  {item: {id: 2, name: "sample"}, amount: 2}, 
  {item: {id: 1, name: "sample"}, amount: 2}, 
  {item: {id: 3, name: "sample"}, amount: 2}, 
  {item: {id: 3, name: "newitem"}, amount: 6}, 
  {item: {id: 3, name: "newitem"}, amount: 1}
];

result should be this

[
  {item: {id: 1, name: "sample"}, amount: 3}, 
  {item: {id: 2, name: "sample"}, amount: 2}, 
  {item: {id: 3, name: "sample"}, amount: 2}, 
  {item: {id: 3, name: "newitem"}, amount: 7}
]
Rick
  • 4,030
  • 9
  • 24
  • 35
daniel
  • 1
  • 1

2 Answers2

0

Pretty much the same as this.

var arr = [
  {item: {id: 1, name: "sample"}, amount: 1}, 
  {item: {id: 2, name: "sample"}, amount: 2}, 
  {item: {id: 1, name: "sample"}, amount: 2}, 
  {item: {id: 3, name: "sample"}, amount: 2}, 
  {item: {id: 3, name: "newitem"}, amount: 6}, 
  {item: {id: 3, name: "newitem"}, amount: 1}
];

var res = {};
arr.map((e) => {
  if(!res[e.item.id]) res[e.item.id] = Object.assign({},e);
  else res[e.item.id].amount += e.amount;
});
console.log(Object.values(res));
SirPilan
  • 4,649
  • 2
  • 13
  • 26
0

Group the input array by a combination of id and name as unique key with Array.prototype.reduce and map out the result with the Array.prototype.map over the keys of the grouped object:

var arr=[{item:{id:1,name:"sample"},amount:1},{item:{id:2,name:"sample"},amount:2},{item:{id:1,name:"sample"},amount:2},{item:{id:3,name:"sample"},amount:2},{item:{id:3,name:"newitem"},amount:6},{item:{id:3,name:"newitem"},amount:1}];

var grouppedObj = arr.reduce((all, {item: {id, name}, amount}) => {

    var key = `${id}${name}`;
    if (!all.hasOwnProperty(key)) all[key] = {item: { id, name }, amount: 0};
    all[key].amount += amount;

    return all;

}, {});

var result = Object.keys(grouppedObj).map(k => grouppedObj[k]);

console.log(result);
Leonid Pyrlia
  • 1,594
  • 2
  • 11
  • 14