2016-01-13 41 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。