2017-07-19 65 views
-2

我有一個對象jQuery中希望實現具有類似值的計數陣列jQuery中

obj[{timestamp:1499385600},{timestamp:1499385600},{timestamp:1499385600}, {timestamp:1499299200}, {timestamp:1499299200}, ...] 

現在我需要的對象,其中i將具有特定時間戳作爲名稱,值對所有計數。例如。

{{timestamp: 1499385600, count: 3}, {timestamp: 1499299200, count:2}} 

不能理解如何在這裏迭代循環。 到目前爲止,我已經完成

var newobj={}; 
for(i=0;i<obj.length;i++){ 
    newobj['timestamp']=obj[i].timestamp; 
    newobj['count']=//Not sure what to write here to get the count 
} 

建議表示讚賞。由於

+4

的對象的樣品中有語法錯誤。你能給出一個更清晰的數據樣本 –

+0

是否正確',{timestamp:1499385600]'? – lalithkumar

+0

[{timestamp:1499385600},{timestamp:1499385600},{timestamp:1499385600},{timestamp:1499299200},{timestamp:1499299200},...] ....這是數組 –

回答

1

忽略所有的語法錯誤在你的問題,並採取適當的假設,這可能是你想要做什麼:

var data = [ 
 
    {timestamp:1499385600}, 
 
    {timestamp:1499385600}, 
 
    {timestamp:1499385600}, 
 
    {timestamp:1499299200}, 
 
    {timestamp:1499299200} 
 
]; 
 

 
var groups = data.reduce(function(acc, obj){ 
 
    acc[obj.timestamp] = acc[obj.timestamp] || 0; 
 
    acc[obj.timestamp] += 1; 
 
    return acc; 
 
}, {}); 
 

 
var result = Object.keys(groups).map(function(key) { 
 
    return { 
 
    timestamp : key, 
 
    count : groups[key] 
 
    }; 
 
}); 
 

 
console.log(result);

首先創建一個映射,其保持的計數的軌跡使用Array#reduce然後使用Object.keys()Array#map

+0

謝謝阿布舍克。它爲我工作。 –

0

幫助創建最終數組R上的循環爲您想newObj看起來是這樣的:

{ 
    '1499385600':6, 
    '1499299200':2 
} 

然後你可以遍歷newObj來創建新的數組,你想

// create counter object 
var newobj = {}; 
for(var i = 0; i < obj.length; i++){ 
    // use current object timestamp as key 
    // if undefined (first time found) make it zero +1 
    // otherwise add 1 to prior count         
    newobj[obj[i].timestamp] = (newobj[obj[i].timestamp] || 0) +1; 
} 
// create results array from counter object 
var results = []; 
for(var time in newObj){ 
    results.push({ timestamp: time, count: newObj[time] }); 
}