How to sum the array of object values and assigned them to the relevant key name

Solution 1:

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)

Solution 2:

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);
}