i have an object like this, how can i calculate total value of code and codePrev :
{
"code01Prev": 3756743628,
"code01": 10346000,
"code02Prev": 0,
"code02": 0,
"code10Prev": 3756743628,
"code10": 10346000,
"code11Prev": 0,
"code11": 0,
"code20Prev": 3756743628,
"code20": 10346000
}
CodePudding user response:
Going with plain vanilla. The code is a little bit imperative (not explaining what but how). If possible it would be good to consider changing data structure.
data = {
code01Prev: 3756743628,
code01: 10346000,
code02Prev: 0,
code02: 0,
code10Prev: 3756743628,
code10: 10346000,
code11Prev: 0,
code11: 0,
code20Prev: 3756743628,
code20: 10346000
}
initialTotals = {
code: 0,
codePrev: 0}
dataKeyValues = Object.entries(data)
totals = dataKeyValues.reduce(
(totalAccumulated, [key, value]) => {
if (key.endsWith('Prev')){
return {
...totalAccumulated,
codePrev: totalAccumulated.codePrev value}}
return {
...totalAccumulated,
code: totalAccumulated.code value}},
initialTotals)
console.log(totals)
// totals:
// {
// "code": 31038000,
// "codePrev": 11270230884
// }