【问题标题】:How to accumulate previous values in array of objects in TypeScript如何在 TypeScript 中的对象数组中累积先前的值
【发布时间】:2021-12-22 06:38:42
【问题描述】:

我需要从一个对象数组中累积以前的值:

"registries": [
    {
      "period_range": "06:00 - 07:00",
      "timestamp": "2021-11-09T09:45:00.000Z",
      "production": {
        "D": 4,
        "P": 3
      },
      "accumulated": {
        "D": 0,
        "P": 0
      },
    },
]

在“累积”对象中,我需要获取所有之前的“生产”值,并与当前生产相加

例子:

如果生产 D 是早上 5 点 5 点,早上 6 点 3 点,那么早上 7 点的累计需要是 5 + 3 和 + 本期的产量。

【问题讨论】:

标签: arrays typescript


【解决方案1】:

Object.values() 获取值,Array.prototype.reduce() 添加所有值。

let registries = [
    {
      "period_range": "06:00 - 07:00",
      "timestamp": "2021-11-09T09:45:00.000Z",
      "production": {
        "D": 4,
        "P": 3
      },
      "accumulated": {
        "D": 0,
        "P": 0
      },
    },
];

const reducer = (previousValue, currentValue) => previousValue + currentValue;
const addAllValues = (where) => Object.values(where).reduce(reducer);

let reg = registries[0];
let result = addAllValues(reg.production) + addAllValues(reg.accumulated);

console.log(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多