2016-01-13 64 views
3

我有对象的一个​​这样的数组:javascript对象上清点相似性质

[{"ts":"Thu, 20 Aug 2015 18:00:00 GMT"}, 
{"ts":"Thu, 20 Aug 2015 17:00:00 GMT"}, 
{"ts":"Thu, 20 Aug 2015 16:00:00 GMT"}, 
{"ts":"Thu, 20 Aug 2015 15:00:00 GMT"}, 
{"ts":"Wed, 19 Aug 2015 16:00:00 GMT"}, 
{"ts":"Wed, 19 Aug 2015 15:00:00 GMT"}] 

我使用像这样通过每次遍历:

_.each(times,function(t){ 
    console.log(t.ts); 
}, this); 

我使用moment到确保日期都具有相同的白天结束时间,以便忽略此变量。我想用相同的次数创建一个新的对象,例如

uniqueTimes = 
{ 
{"Thu, 20 Aug 2015": 4}, 
{"Wed, 19 Aug 2015": 2} 
} 

有关如何做到这一点的任何建议?我正在考虑遍历_.each函数中的uniqueTimes对象,但我有数百次,所以每次迭代uniqueTimes都会越来越大。这看起来效率不高。

回答

2

根据您对_.each的使用情况,您似乎在使用LoDash或Underscore。在这种情况下,两个库都有一个方便的_.countBy方法(LoDash docsUnderscore docs),可以让您得到您想要的结果,如下所示。

除了我正在使用的整个拆分/连接方法,您还可以使用adeneo shared的正则表达式方法。

var times = [{"ts":"Thu, 20 Aug 2015 18:00:00 GMT"}, 
 
{"ts":"Thu, 20 Aug 2015 17:00:00 GMT"}, 
 
{"ts":"Thu, 20 Aug 2015 16:00:00 GMT"}, 
 
{"ts":"Thu, 20 Aug 2015 15:00:00 GMT"}, 
 
{"ts":"Wed, 19 Aug 2015 16:00:00 GMT"}, 
 
{"ts":"Wed, 19 Aug 2015 15:00:00 GMT"}]; 
 

 
var groupedCounts = _.countBy(times, function(item) { 
 
    var split = item.ts.split(' '); 
 
    var value = split.slice(0, split.length - 2).join(' '); 
 
    return value; 
 
}); 
 

 
document.body.innerHTML = '<pre>' + JSON.stringify(groupedCounts, null, 2) + '</pre>';
<script src="https://cdn.rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>

+0

是的,你是正确的,我是新来的吧,所以我只是学习工具。感谢您指出'_.countBy'。这给了我一个关于如何继续处理绘制这些数据的问题的好主意,到目前为止我已经得到了很好的结果。 – thehme

1

您只需迭代,并添加独特的时间,当您去

var times = [ 
 
    {"ts":"Thu, 20 Aug 2015 18:00:00 GMT"}, 
 
    {"ts":"Thu, 20 Aug 2015 17:00:00 GMT"}, 
 
    {"ts":"Thu, 20 Aug 2015 16:00:00 GMT"}, 
 
    {"ts":"Thu, 20 Aug 2015 15:00:00 GMT"}, 
 
    {"ts":"Wed, 19 Aug 2015 16:00:00 GMT"}, 
 
    {"ts":"Wed, 19 Aug 2015 15:00:00 GMT"} 
 
]; 
 

 
var uniqueTimes = {}; 
 

 
times.forEach(function(time) { 
 
    var t = (time.ts.match(/^(.*?)\s\d+\:/) || [])[1]; 
 
    
 
    t in uniqueTimes ? uniqueTimes[t]++ : uniqueTimes[t] = 1; 
 
}); 
 

 
document.body.innerHTML = '<pre>' + JSON.stringify(uniqueTimes, null, 4) + '</pre>';

1

随着ES6可以使用Map()数据结构,你的任务:

const result = data.reduce((m, i) => { 
    const key = i.ts; // or format your date with moment 
    return m.set(key, m.has(key) ? m.get(key) + 1 : 1); 
}, new Map()); 

console.log(result); 

公告:在你的环境中检查Map compability。