2017-07-19 23 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] }); 
}