我想结合并计算日期。所有日期都在UTC时区,我首先使用toLocaleDateString()将所有UTC时间转换为本地时间,然后将该日期作为JSON对象的键,但不能按预期获得结果。
我的JSON格式:
[{"UploadTimeStamp":"2017-02-18T09:01:43.060Z"},
{"UploadTimeStamp":"2017-02-19T04:09:43.347Z"},
{"UploadTimeStamp":"2017-02-21T14:38:40.157Z"},
{"UploadTimeStamp":"2017-02-22T11:30:58.546Z"},
{"UploadTimeStamp":"2017-02-22T11:31:35.514Z"},
{"DoneTimeStamp":"2017-02-19T03:54:34.791Z"},
{"DoneTimeStamp":"2017-02-19T17:48:40.041Z"},
{"DoneTimeStamp":"2017-02-21T14:55:33.335Z"},
{"DoneTimeStamp":"2017-02-17T15:01:32.426Z"}]
结果:
{"18/02/2017":{"Upload":1},
"19/02/2017":{"Upload":1},
"21/02/2017":{"Upload":1},
"22/02/2017":{"Upload":"[object Object]1","Done":"[object Object]1"},
"17/02/2017":{"Done":1}}
我的代码:
for (var i = 0; i < result.length; i++) {
if (result[i].UploadTimeStamp) {
var value = new Date(result[i].UploadTimeStamp).toLocaleDateString();
//increment counter for this value (starting at 1)
var count = (temp[value] || 0) + 1;
if (temp[value] === undefined) {
temp[value] = {}
temp[value].Upload = count;
}
else {
temp[value].Upload = count;
}
}
else {
var value = new Date(result[i].DoneTimeStamp).toLocaleDateString();
//increment counter for this value (starting at 1)
var count = (temp[value] || 0) + 1;
if (temp[value] === undefined) {
temp[value] = {}
temp[value].Done = count;
}
else {
temp[value].Done = count;
}
}
}
console.log(JSON.stringify(temp))
我的预期结果
{"18/02/2017":{"Upload":1,"Done":0},
"19/02/2017":{"Upload":1,"Done":2},
"21/02/2017":{"Upload":1,"Done":1},
"22/02/2017":{"Upload":1,"Done":1},
"17/02/2017":{"Done":1,"Upload":0}}
提前谢谢
答案 0 :(得分:2)
var data = [{"UploadTimeStamp":"2017-02-18T09:01:43.060Z"},
{"UploadTimeStamp":"2017-02-19T04:09:43.347Z"},
{"UploadTimeStamp":"2017-02-21T14:38:40.157Z"},
{"UploadTimeStamp":"2017-02-22T11:30:58.546Z"},
{"UploadTimeStamp":"2017-02-22T11:31:35.514Z"},
{"DoneTimeStamp":"2017-02-19T03:54:34.791Z"},
{"DoneTimeStamp":"2017-02-19T17:48:40.041Z"},
{"DoneTimeStamp":"2017-02-21T14:55:33.335Z"},
{"DoneTimeStamp":"2017-02-17T15:01:32.426Z"}];
var tmp = {};
data.forEach(function(d){
let key = Object.keys(d)[0];
let value = new Date(d[key]).toLocaleDateString();
key === "UploadTimeStamp" ? key = "upload": key = "done";
tmp[value] = tmp[value] || {};
tmp[value].upload = tmp[value].upload || 0;
tmp[value].done = tmp[value].done || 0;
tmp[value][key] += 1;
});
console.log(tmp);
答案 1 :(得分:2)
您没有检查.Done或.Upload是否未定义,而是该日期的整个对象。检查设置var count的行。
realmObject