Search code examples
javascriptarraysjavascript-objects

Merge objects in a single objects array


I have an array with multiple objects as shown below

[{Name: "Product A", Qty: "5"}, {Name: "Product B", Qty: "2"}, {Name: "Product A", Qty: "6"}]

and was wondering how I can merge the object QTY field values in related product NAME to produce a new array like that shown below:

[{Name: "Product A", Qty: "11"}, {Name: "Product B", Qty: "2"}]

Any help with this would be much appreciated. Thanks


Solution

  • You could use reduce to create one object and get values with Object.values.

    const data = [{Name: "Product A", Qty: "5"}, {Name: "Product B", Qty: "2"}, {Name: "Product A", Qty: "6"}]
    
    const result = data.reduce((r, {Name, Qty}) => {
      if(!r[Name]) r[Name] = {Name, Qty: +Qty};
      else r[Name].Qty += +Qty;
      return r;
    }, {})
    
    console.log(Object.values(result))