我有一个像这样的json示例:
[
{"emp_name":"ABC","works_on":"wheels","time_from":"2012-03-27 10:00:00","time_to":"2012-03-27 12:00:00"},
{"emp_name":"xyz","works_on":"seat","time_from":"2012-03-27 14:00:00","time_to":"2012-03-27 17:00:00"},
{"emp_name":"ABC","works_on":"painting","time_from":"2012-03-28 10:00:00","time_to":"2012-03-28 12:00:00"},
{"emp_name":"xyz","works_on":"tube","time_from":"2012-03-28 14:00:00","time_to":"2012-03-28 17:00:00"},
{"emp_name":"pqr","works_on":"engine","time_from":"2012-03-29 10:00:00","time_to":"2012-03-29 12:00:00"},
{"emp_name":"ABC","works_on":"wiper","time_from":"2012-03-29 14:00:00","time_to":"2012-03-29 17:00:00"},
{"emp_name":"mno","works_on":"air_cooler","time_from":"2012-03-30 10:00:00","time_to":"2012-03-30 12:00:00"},
{"emp_name":"ABC","works_on":"wheels","time_from":"2012-03-30 14:00:00","time_to":"2012-03-30 17:00:00"},
]
我不知道是否有办法计算每个雇主的总工作时数。
答案 0 :(得分:2)
如果我正确理解了您的问题,您需要计算每个emp_name
的总工作时间。
只需要使用此代码:
var data = [
{ "emp_name": "ABC", "works_on": "wheels", "time_from": "2012-03-27 10:00:00", "time_to": "2012-03-27 12:00:00" },
{ "emp_name": "xyz", "works_on": "seat", "time_from": "2012-03-27 14:00:00", "time_to": "2012-03-27 17:00:00" },
{ "emp_name": "ABC", "works_on": "painting", "time_from": "2012-03-28 10:00:00", "time_to": "2012-03-28 12:00:00" },
{ "emp_name": "xyz", "works_on": "tube", "time_from": "2012-03-28 14:00:00", "time_to": "2012-03-28 17:00:00" },
{ "emp_name": "pqr", "works_on": "engine", "time_from": "2012-03-29 10:00:00", "time_to": "2012-03-29 12:00:00" },
{ "emp_name": "ABC", "works_on": "wiper", "time_from": "2012-03-29 14:00:00", "time_to": "2012-03-29 17:00:00" },
{ "emp_name": "mno", "works_on": "air_cooler", "time_from": "2012-03-30 10:00:00", "time_to": "2012-03-30 12:00:00" },
{ "emp_name": "ABC", "works_on": "wheels", "time_from": "2012-03-30 14:00:00", "time_to": "2012-03-30 17:00:00" }
];
此功能d3.nest().key(function (d) { return d.emp_name })
会按emp_name
对您的数据进行分组。
var nest = d3.nest().key(function (d) { return d.emp_name })
.rollup(function(v) {
return d3.sum(v, function (d) {
//Convert time to standard format
var sTimeTo = d.time_to;
var splitedTimeTo = sTimeTo.split(" ");
splitedTimeTo = splitedTimeTo[0] + "T" + splitedTimeTo[1];
var sTimeFrom = d.time_from;
var splitedTimeFrom = sTimeFrom.split(" ");
splitedTimeFrom = splitedTimeFrom[0] + "T" + splitedTimeFrom[1];
//cal difference between time_to and tim_from
var timeTo = Date.parse(splitedTimeTo);
var timeFrom = Date.parse(splitedTimeFrom);
var deltaTime = timeTo - timeFrom;
//convert date from milli s to an hour
deltaTime = Math.ceil(deltaTime / (1000 * 3600));
console.log(deltaTime);
return deltaTime;
});
})
.entries(data);
console.log(JSON.stringify(nest));
完成jsfiddel here。