如何在js中计算一个对象每2个值的总和
How to calculate sum of an object each 2 its value in js
我有一个这样的对象,我如何计算代码和codePrev的总值:
{
"code01Prev": 3756743628,
"code01": 10346000,
"code02Prev": 0,
"code02": 0,
"code10Prev": 3756743628,
"code10": 10346000,
"code11Prev": 0,
"code11": 0,
"code20Prev": 3756743628,
"code20": 10346000
}
选择普通香草。该代码有点强制性(不解释是什么,而是如何解释)。如果可能,最好考虑更改数据结构。
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
// }
我有一个这样的对象,我如何计算代码和codePrev的总值:
{
"code01Prev": 3756743628,
"code01": 10346000,
"code02Prev": 0,
"code02": 0,
"code10Prev": 3756743628,
"code10": 10346000,
"code11Prev": 0,
"code11": 0,
"code20Prev": 3756743628,
"code20": 10346000
}
选择普通香草。该代码有点强制性(不解释是什么,而是如何解释)。如果可能,最好考虑更改数据结构。
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
// }