Javascript object group by day,month,year

前端 未结 2 1068
星月不相逢
星月不相逢 2021-01-06 15:06

I am working on application which I need to do grouping of different sets of javascript object and those will be based on month,day and year.

For day I am doing like

2条回答
  •  情书的邮戳
    2021-01-06 15:30

    Please see if the following refactor is useful for you http://jsfiddle.net/wkUJC/

    var dates = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];
    
    function calc(dates) {
        var response = {};
        dates.forEach(function(d){
            for (var k in d) {
                var _ = k.split("-");
                var year = _[0]
                var month = _[1]
                if (!response[year]) response[year] = {total: 0}
                response[year][month] = response[year][month] ? response[year][month]+d[k] : d[k]
                response[year].total+= d[k]
            }
        });
        console.log(response);
        return response;
    }
    
    calc(dates);
    

提交回复
热议问题