Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading