Let's say I have an array of objects and want to group these by a specified key: 'name', and sum all of their values into one object:
[
{
name: "test1",
value1: 100,
value2: 100,
value3: 100
},
{
name: "test1",
value1: 100,
value2: 100,
value3: 100
},
{
name: "test2",
value1: 200,
value2: 100,
value3: 100
},
{
name: "test2",
value1: 200,
value2: 100,
value3: 100
},
{
name: "test3",
value1: 100,
value2: 100,
value3: 100
}
]
And the result I want would have this structure:
[
{
name: "test1",
value1: 200,
value2: 200,
value3: 200
},
{
name: "test2",
value1: 400,
value2: 200,
value3: 200
},
{
name: "test3",
value1: 100,
value2: 100,
value3: 100
}
]
How would I go about doing this? I can currently get the sum of one key by using this method:
const total_sum_data = (arr, key, value) => {
const map = new Map();
for (const obj of arr) {
const currSum = map.get(obj[key]) || 0;
map.set(obj[key], currSum + obj[value]);
}
const res = Array.from(map, ([k, v]) => ({ [key]: k, [value]: v }));
return res;
};
But not sure how to merge the results into one object with the specified key.