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

Time:01-21

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?

CodePudding user response:

solved using reduce and forEach

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)

CodePudding user response:

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

CodePudding user response:

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

  1. Extract only the incomes from the data array
  2. For each income object, get the key-value pair and transform into another object of the structure {key: 20yy-mm, value: nn}
  3. Use .flat() to transform the result from step-2 into a 1-dimensional array
  4. Use .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());

CodePudding user response:

My approach here is to destructure the array. This way I have all the data of the incomes of group A in the variable A and the same for B.

Then I loop through both objects and see if the dates match, if so, sum the incomes and add the data to the total object.

const data = [
  {
    group: 'A',
    incomes: { "2019-12": 100, "2020-12": 200, "2021-12": 15 }
  },
  {
    group: 'B',
    incomes: { "2019-12": 25, "2020-12": 50 }
  }
]

let A, B, total = {};

[A, B] = [data[0].incomes, data[1].incomes]

for(const date in A){
  for(const d in B){
   total[date] = date === d ? A[date]   B[date] : A[date]
  }  
}

console.log(total)

  •  Tags:  
  • Related