1

I have an array with product objects in Javascript. I want to check in this array if there are product objects with the same id. If so, I want to merge the product objects to one and add up the values from the count field.

let products = [ 
   { id: 1, name: product1, count: 2 }
   { id: 2, name: product2, count: 2 }
   { id: 3, name: product3, count: 2 }
   { id: 4, name: product4, count: 2 }
   { id: 1, name: product4, count: 2 }
   { id: 2, name: product4, count: 2 }]

This is the result I want:

let products = [ 
{ id: 1, name: product1, count: 4 }
{ id: 2, name: product2, count: 4 }
{ id: 3, name: product3, count: 2 }
{ id: 4, name: product4, count: 2 }]

Can anybody tell me the best way how I can do this? I'm using Lodash in my project.

Thanks in advance!

GKK
  • 11
  • 2

0 Answers0