There exists an array of objects like so where there is a 'category' key and some 'series' keys.
arrOne = [
{
"series_1": 25,
"category": "Category 1",
"series_2": 50
},
{
"series_1": 11,
"category": "Category 2",
"series_2": 22
},
{
"series_1": 32,
"category": "Category 1",
"series_2": 74
},
{
"series_1": 74,
"category": "Category 3",
"series_2": 98
},
{
"series_1": 46,
"category": "Category 3",
"series_2": 29
},
]
(Note that 'category' can be pretty much any value, though there will likely be multiple similar values as well as some unique values e.g. there are multiple objects with 'category' value 'Category 3' but only 1 with 'category' value 'Category 2')
The following lines of code will add up all of series_1 for objects with the same category
var objForAllCategories = {};
this.arrOne.forEach(item => {
if (objForAllCategories.hasOwnProperty(item.category))
objForAllCategories[item.category] = objForAllCategories[item.category] + item.series_1;
else
objForAllCategories[item.category] = item.series_1;
});
for (var prop in objForAllCategories) {
this.allCategoriesAndValues.push({
category: prop,
series_1: objForAllCategories[prop]
});
}
So it would result in:
allCategoriesAndValues = [
{
"category": "Category 1",
"series_1": 57 // 25 + 32 adding up series_1 from all 'Category 1' items in arrOne
},
{
"category": "Category 2",
"series_1": 11 // only 1 'Category 2' from arrOne
},
{
"category": "Category 3",
"series_1": 120 // 74 + 46 adding up series_1 from all 'Category 3' items in arrOne
}
]
However, I want to be able to add not just series_1 but also all other items.
This example only has category and series_1 and series_2 as keys. However, there could be:
- series_3
- series_4
- series_5
- series_6
- series_7
- etc..
How can I account for all potential series_x?
Intended result:
allCategoriesAndValues = [
{
"category": "Category 1",
"series_1": 57,
"series_2": 124,
..... if 'series_3', 'series_4' etc. existed, it would be included in this as above
},
{
"category": "Category 2",
"series_1": 11,
"series_2": 22,
..... if 'series_3', 'series_4' etc. existed, it would be included in this as above
},
{
"category": "Category 3",
"series_1": 120,
"series_2": 127,
..... if 'series_3', 'series_4' etc. existed, it would be included in this as above
}
]