我正在使用 JavaScript。我有一个包含这种格式数据的数组:
[
{"USER_NAME":"User1","LAST_SUCCESSFUL_CONNECT":"1373978337642"},
{"USER_NAME":"User2","LAST_SUCCESSFUL_CONNECT":"1374515704026"},
{"USER_NAME":"User3","LAST_SUCCESSFUL_CONNECT":"1374749782479"}
]
(上面的数字代表以毫秒为单位的 UTC 日期/时间。
我想按月对数据进行分组(计数)。像这样:
[
{"Month":"January, 2014","User_Count": 2},
{"Month":"February, 2014","User_Count": 1},
]
我可以使用 jQuery如果它简化了事情。
最佳答案
这看起来像一个 map
reduce
问题。高级解决方案如下:
- 重新组织列表中的成员。
- 数一数。
这是实现此目标的分步操作方法:
map
- 遍历字典列表
- 将日期时间字符串转换为 javascript 日期时间对象。
- 使用月-年作为键,使用字典列表作为值。
这些现在按月-年分组。
示例:
var l = [...];
var o = {};
var f = function(x){
var dt_object = Date(x["LAST_SUCCESSFUL_CONNECT"]); // convert to datetime object
var key = dt_object.year + '-' + dt_object.month;
if (o[key] === undefined) {
var o[key] = [];
};
o[key].push(x)
}
_.map(l, f(x)) //apply f to each member of l
减少
- 遍历包含列表字典的新对象。
- 计算每个字典列表的长度。
- 使用
count
作为键,列表的长度作为它的值。
示例:
var g = function(member_count){
//extra logic may go here
return member_count
}
for member in o {
count = _.reduce(l, g(member))
member['count'] = count
}
生成的 API
o['month-year'] //for list of dictionaries in that month
o['month-year']['count'] //for the count of list of dictionaries in that month.
引用资料:
对于 javascript 中的 map
和 reduce
函数,请参阅 underscore.js:
http://underscorejs.org/#map
http://underscorejs.org/#reduce
Javascript 日期对象:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
有关 Date 和 DateTime 对象的更多信息:
https://en.wikipedia.org/wiki/ISO_8601
有关map
reduce
的更多信息:
https://en.wikipedia.org/wiki/MapReduce
关于javascript - 如何按月对一组对象进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17860382/