按公共日期汇总对象数组中的数据

时间:2020-07-16 10:59:09

标签: javascript

这是我的数据, “时间”是数字

[
    {
        "time": 202007150800,
        "count": 10
    },
    {
        "time": 202007160700,
        "count": 11
    },
    {
        "time": 202007160900,
        "count": 12
    }
]

如何使用从昨天8点到今天8点的“时间”组数据求和“计数” ,例如7/15数据是7/15 08:00-7/16 07:00

像这样:

[
    {
        "time": 20200715,
        "count": 21
    },
    {
        "time": 20200716,
        "count": 12
    }
 ]

1 个答案:

答案 0 :(得分:1)

尝试使用此功能

function mapData(data) {

    let result = [];

    data.forEach(element => {
        let t = element.time + 9200;

        let substr = t.toString().substr(0, 8);
        if(!result[substr])
            result[substr] = 0;
        result[substr] += element.count;
    });

    let returnResult = [];

    result.forEach((element, index) =>
        returnResult.push({
            time: index,
            count: element
        })
    );
    return returnResult;
}