Javascript how to merge objects with same product id and summarize quantity

I have a cart with a bunch of products, based on this array:

[
  { 
     product_id: 123,
     price: 100,
     quantity: 1,
     item: { ... some more data }
  },
  { 
     product_id: 200,
     price: 199,
     quantity: 1,
     item: { ... some more data }
  },
  { 
     product_id: 123,
     price: 100,
     quantity: 2,
     item: { ... some more data }
  },
  etc...
]

So, when a product has been added multiple times, it should "merge" them into one object and the output to be like:

[
  { 
     product_id: 123,
     price: 100,
     **quantity: 2,** // THIS IS VERY IMPORTANT
     item: { ... some more data }
  },
  { 
     product_id: 200,
     price: 199,
     quantity: 1,
     item: { ... some more data }
  },
]

So, I’ve tried the following:

const output = Object.values(
  items.reduce((accu, { product_id, ...item }) => {
    if (!accu[product_id]) accu[product_id] = {}
    accu[product_id] = { product_id, ...accu[product_id], ...item }
    return accu
  }, {}),
)

this actually gives me what I want, EXCEPT that the quantity is summarized.

How can I achieve that?

>Solution :

You have to add the accumulation logic to the quant separately

like the following example

const cart = [
  { 
     product_id: 123,
     price: 100,
     quantity: 1,
    
  },
  { 
     product_id: 200,
     price: 199,
     quantity: 1,
     
  },
  { 
     product_id: 123,
     price: 100,
     quantity: 2,
    
  },
  
]

const output = Object.values(
  cart.reduce((accu, { product_id, ...item }) => {
  
    if (!accu[product_id]) accu[product_id] = 
    {
      quantity:0
    }
    
    accu[product_id] = { 
      product_id,
      ...accu[product_id],
      ...item,
      quantity: accu[product_id].quantity + item.quantity // custom accu for quant
    }
    
    return accu;
  }, {}),
)

console.log(output)

Leave a Reply