Sum values of objects with same keys

I have a data structure like this one.
It’s basiccally an array of objects.

const dataset = [
  {
    a: { total: 2, name: "red" },
    b: { total: 3, name: "gold" },
    c: { total: 6, name: "rose" },
  },
  {
    a: { total: 10, name: "red" },
    b: { total: 7, name: "purple" },
  },
  {
    a: { total: 1, name: "pink" },
    b: { total: 14, name: "blue" },
    c: { total: 10, name: "rose" },
  },
  {
    b: { total: 2, name: "green" },
    c: { total: 18, name: "rose" },
  },
]

This is what I would like to compute as result:

const result = { 
  a: 13, 
  b: 26, 
  c: 34, 
}

So, I need a sum of values total by objects with same key.I try to explain myself using the previous example:

const result = { 
  a: 13, // 2 + 10 + 1
  b: 26, // 3 + 7 + 14 + 2
  c: 34, // 6 + 10 + 18
}

Note that the keys a, b, c can be a lot (not only 3) and I don’t know their name because they are dynamic.

How can I do that? I thought to group the objects {total, name} by keys and then sum by total but how? Is there a Lodash function that can help me?

>Solution :

Why not use reduce with for of:

const dataset = [{a: { total: 2, name: "red" }, b: { total: 3, name: "gold" }, c: { total: 6, name: "rose" }, }, {a: { total: 10, name: "red" }, b: { total: 7, name: "purple" }, }, {a: { total: 1, name: "pink" }, b: { total: 14, name: "blue" }, c: { total: 10, name: "rose" }, }, {b: { total: 2, name: "green" }, c: { total: 18, name: "rose" }, }, ];

const result = dataset.reduce((res, cur) => {
    for (const [key, value] of Object.entries(cur)) {
      res[key] = (res[key] || 0) + value.total;
    }
    return res;
}, {});

console.log(result);

Leave a Reply