我在jQuery中有一个对象
obj[{timestamp:1499385600},{timestamp:1499385600},{timestamp:1499385600}, {timestamp:1499299200}, {timestamp:1499299200}, ...]
现在我需要一个对象,我将具有特定时间戳的所有计数作为名称,值对。例如。
{{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
}
建议表示赞赏。感谢
答案 0 :(得分: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
的帮助下创建最终数组答案 1 :(得分:0)
循环完成后,您希望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] });
}