I need to understand the simplest way of doing this. I've got an array of objects:
const data = [
{
group: 'A',
incomes: {
"2019-12": 100,
"2020-12": 200,
"2021-12": 15
}
},
{
group: 'B',
incomes: {
"2019-12": 25,
"2020-12": 50,
}
}
]
What I'm trying to get is simple object where its key is the month from data.incomes and the value is sum of relative month values, so the final result looks like:
const totalIncomes = {
"2019-12": 125,
"2020-12": 250,
"2021-12": 15
}
Can anybody explain it to me step by step, please?
solved using reduce and forEach
Inside the reduce function I'm running a forEach on the array of keys of the incomes object/attribute. For each key which is a date I'm checking if the accumulator of the reduce function contains an attribute for each date and creates if not. After creating the attribute I'm summing the value for the current date attribute.
const data = [
{
group: 'A',
incomes: {
"2019-12": 100,
"2020-12": 200,
"2021-12": 15
}
},
{
group: 'B',
incomes: {
"2019-12": 25,
"2020-12": 50,
}
}
]
const totalIncomes = data.reduce((acc,curr)=> {
Object.keys(curr.incomes).forEach((key, index) => {
if(!acc[key]){
acc[key] = 0;
}
acc[key]+=curr.incomes[key]
});
return acc;
},{})
console.log(totalIncomes)
Maybe this is not the pretties solutions but you can do it like this, the function is of course not necessary.
const data = [
{
group: "A",
incomes: {
"2019-12": 100,
"2020-12": 200,
"2021-12": 15,
},
},
{
group: "B",
incomes: {
"2019-12": 25,
"2020-12": 50,
},
},
];
getterInformation(data);
function getterInformation(object) {
let objectWithCalculatedValues = {};
object.forEach((items) => {
for (const key in items.incomes) {
if (objectWithCalculatedValues[key] === undefined) {
objectWithCalculatedValues[key] = 0;
}
objectWithCalculatedValues[key] += items.incomes[key];
}
});
console.log(objectWithCalculatedValues);
}
Assuming that this information may be useful to readers who may be unable to obtain necessary guidance (due to various possible reasons), here is one possible way to achieve the objective (solution):
const aggregateIncomesByMonth = () => (
data.map(d => Object.entries(d.incomes).map(([k, v]) => ({
key: k,
value: v
}))).flat().reduce((fin, itm) => ({
...fin,
[itm.key]: (fin[itm.key] || 0) + itm.value
}), {})
);
Explanation
incomes from the data arrayincome object, get the key-value pair and transform into another object of the structure {key: 20yy-mm, value: nn}.flat() to transform the result from step-2 into a 1-dimensional array.reduce to sum the value for those cases where the key (ie, 20yy-mm) matches.Code-snippet
const data = [{
group: 'A',
incomes: {
"2019-12": 100,
"2020-12": 200,
"2021-12": 15
}
},
{
group: 'B',
incomes: {
"2019-12": 25,
"2020-12": 50,
}
}
];
const aggregateIncomesByMonth = () => (
data.map(d => Object.entries(d.incomes).map(([k, v]) => ({
key: k,
value: v
}))).flat().reduce((fin, itm) => ({
...fin,
[itm.key]: (fin[itm.key] || 0) + itm.value
}), {})
);
console.log(aggregateIncomesByMonth());