大家好,
我有这个对象:
{"2017-07-09 00:00:00":4,"2017-07-09 09:00:00":1,"2017-07-09 10:00:00":4,"2017-07-09 11:00:00":3,"2017-07-09 12:00:00":16,"2017-07-09 13:00:00":4,"2017-07-09 14:00:00":6,"2017-07-09 15:00:00":5,"2017-07-09 16:00:00":7,"2017-07-09 17:00:00":21,"2017-07-09 18:00:00":25,"2017-07-09 19:00:00":1,"2017-07-10 09:00:00":11,"2017-07-10 10:00:00":4,"2017-07-10 11:00:00":21,"2017-07-10 12:00:00":22,"2017-07-10 13:00:00":23,"2017-07-10 14:00:00":42,"2017-07-10 15:00:00":14,"2017-07-10 16:00:00":36,"2017-07-10 17:00:00":21,"2017-07-10 18:00:00":5,"2017-07-11 09:00:00":16,"2017-07-11 10:00:00":7,"2017-07-11 11:00:00":26,"2017-07-11 12:00:00":34,"2017-07-11 13:00:00":39,"2017-07-11 14:00:00":39,"2017-07-11 15:00:00":30,"2017-07-11 16:00:00":33,"2017-07-11 17:00:00":22,"2017-07-11 18:00:00":1}
我试图每天划分它并得到这样的东西:
首先创建一个24小时的数组:
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
然后计算上面对象的天数并获得每小时的值并返回如下所示的值。在我有3天的对象中,所以我需要每天返回3个数组:
[4,0,0,0,0,0,0,0,0,1,10,3,16,...],
[0,0,0,0,0,0,0,0,0,11,4,21,22,23,42,...]
[0,0,0,0,0,0,0,0,0,16,7,26,34,39,39,30,..]
对于不在对象数据中的每个小时,返回0并且对于存在的每个小时,返回对象上的指定值。
例如,在对象上,时间从"2017-07-09 00:00:00":4
开始,其值为4,并且该值与"2017-07-09 09:00:00":1
之间的每小时
返回0。
任何帮助表示赞赏。非常感谢你的时间
答案 0 :(得分:1)
You have first to loop into each keys of your object
.
After that many solutions, one is to convert your keys into Date
object and compare the hour of your object
in a for
loop.
And retrieve the right data by reconverting your Date obj into your obj property.
Edit
Access your property value without function by using Object.keys
and findIndex
I've maybe misunderstand your requirement, but you've a good example of how to do ;-)
Example of solution
var data ={"2017-07-09 00:00:00":4,"2017-07-09 09:00:00":1,"2017-07-09 10:00:00":4,"2017-07-09 11:00:00":3,"2017-07-09 12:00:00":16,"2017-07-09 13:00:00":4,"2017-07-09 14:00:00":6,"2017-07-09 15:00:00":5,"2017-07-09 16:00:00":7,"2017-07-09 17:00:00":21,"2017-07-09 18:00:00":25,"2017-07-09 19:00:00":1,"2017-07-10 09:00:00":11,"2017-07-10 10:00:00":4,"2017-07-10 11:00:00":21,"2017-07-10 12:00:00":22,"2017-07-10 13:00:00":23,"2017-07-10 14:00:00":42,"2017-07-10 15:00:00":14,"2017-07-10 16:00:00":36,"2017-07-10 17:00:00":21,"2017-07-10 18:00:00":5,"2017-07-11 09:00:00":16,"2017-07-11 10:00:00":7,"2017-07-11 11:00:00":26,"2017-07-11 12:00:00":34,"2017-07-11 13:00:00":39,"2017-07-11 14:00:00":39,"2017-07-11 15:00:00":30,"2017-07-11 16:00:00":33,"2017-07-11 17:00:00":22,"2017-07-11 18:00:00":1}
var dataKeys = Object.keys(data);
var dataKeysParsed = dataKeys.map(function(d){
return new Date(d);
});
var res =[];
for (var i=0;i<=23;i++){
var id = dataKeysParsed.findIndex(function(k){
return k.getHours() == i
});
res.push(id > -1 ? data[dataKeys[id]] : 0);
}
console.log(res);