按天,月,年Javascript对象组 [英] Javascript object group by day,month,year

查看:117
本文介绍了按天,月,年Javascript对象组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的应用程序,我需要做套不同的JavaScript对象的分组和那些将根据月,日和年。

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.

有关一天我做像下面

var calculateByDay = function(inputList){
        var outPutList = [];    
        var result = {}
        var item = null, key = null;
        for(i=0; c<inputList.length; i++) {
           item=inputList[c];
           key = Object.keys(item)[0];
           item=item[key];
           if(!result[key]) {
                result[key] = item;
            }
           else {
            result[key] += item;
        }
        for (r in result)
            {
                var docs = {};
                docs["date"] = r;
                docs["amount"] = result[r];
                outPutList.push(docs);
            }

        }
        return outPutList;
    }

我如何改善上述code和使用它的月和年计算也?
我去彻底underscore.js,它有一个 GROUPBY 方法。但似乎不符合我的要求相符。
我想GROUP BY个月,今年还,

How can I improve above code and use it for month and year calculation also? I went thorough underscore.js and it has a groupBy method. but seems not fits with my requirement. I want to group by months and year also, for

var inputList = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];

输出应该是:

Monthly :
[{"December 2012": 2000}, {"January 2013": 1200},{"February 2013": 1550}];
Yearly
[{"year 2012": 2000}, {"year 2013": 2750}];

和看来我需要这样的地图,减少对大数据(阵列组)的做法,是在那里我可以做,使code固体任何其他库或做法?

And it seems I need to this kind of map,reduce approach for large data(array sets), is there any other library or practices I can do to make the code solid?

先谢谢了。

推荐答案

给出一个稍微不同结构的数据:

Given a slightly different structure of data:

var data = [{
  "date": "2011-12-02T00:00",
  "value": 1000
}, {
  "date": "2013-03-02T00:00",
  "value": 1000
}, {
  "date": "2013-03-02T00:00",
  "value": 500
}, {
  "date": "2012-12-02T00:00",
  "value": 200
}, {
  "date": "2013-04-02T00:00",
  "value": 200
}, {
  "date": "2013-04-02T00:00",
  "value": 500
}, {
  "date": "2013-03-02T00:00",
  "value": 500
}, {
  "date": "2013-04-12T00:00",
  "value": 1000
}, {
  "date": "2012-11-02T00:00",
  "value": 600
}];

您可以使用下划线:

var grouped = _.groupBy(data, function(item) {
    return item.date;
});

var groupedByYear = _.groupBy(data, function(item) {
    return item.date.substring(0,4);
});

var groupedByMonth = _.groupBy(data, function(item) {
    return item.date.substring(0,7);
});

console.log(groupedByYear);

请参阅相关的答案:<一href=\"http://stackoverflow.com/questions/16743628/javascript-underscorejs-map-reduce-groupby-based-on-date/16746590#16746590\">Javascript - underscorejs映射减少GROUPBY根据日期

这篇关于按天,月,年Javascript对象组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆