从下面的对象中找到最早开始日期和最晚结束日期的最简单方法是什么?
(对不起 - 我知道已经有很多类似的问题,但我的JS技能很差,而且我无法将任何解决方案应用到我自己的数据中。所以说,代码例子肯定会帮助我解决任何问题 - 谢谢!)
var ganttData = [
{
"id": 123456,
"name": "Sample Project",
"start": new Date(2010,11,6),
"end": new Date(2011,0,6),
"status": "Not Started",
"phase": [
{
"id": 123457,
"name": "Sample Phase",
"start": new Date(2010,11,6),
"end": new Date(2010,11,13),
"status": "Not Started",
"task": [
{
"id": 123458,
"name": "Sample Task",
"start": new Date(2010,11,6),
"end": new Date(2010,11,8),
"status": "Not Started"
}
]
},
{
"id": 123459,
"name": "Another Phase",
"start": new Date(2010,11,13),
"end": new Date(2011,0,20),
"status": "Not Started"
}
]
}
]
答案 0 :(得分:5)
你可以简单地遍历遍历树
var max = new Date(-100000000*86400000);
var min = new Date( 100000000*86400000);
function compare(key,value) {
if (key == "start" && value < min)
min=value;
else if (key == "end" && value > max)
max=value;
}
function traverse(obj, fun) {
for (prop in obj) {
fun.apply(this,[prop, obj[prop]]);
if (typeof(obj[prop]) == "object") {
traverse(obj[prop], fun);
}
}
}
traverse(ganttData, compare);
> max
Thu Jan 20 2011 00:00:00 GMT+0100 (W. Europe Standard Time)
> min
Mon Dec 06 2010 00:00:00 GMT+0100 (W. Europe Standard Time)
上述内容有效,直到您将开始和结束从Date
更改为string
。现在你必须做这样的事情
arr = "2010,11,13".split(",");
date = new Date(arr[0], arr[1], arr[2]);
之前比较。
我从JavaScript Reference中获得了反转的min and max dates。
答案 1 :(得分:1)
function getEarliestAndLatest(ganttData) {
var earliest = ganttData.start,
latest = ganttData.end,
phase,
task;
for (var i = 0, countPhases = ganttData.phase.length; i < countPhases; i++) {
phase = ganttData.phase[i];
if (phase.start < earliest) {
earliest = phase.start;
}
if (phase.end > latest) {
latest = phase.end;
}
if (typeof phase.task !== 'undefined') {
for (var j = 0, countTasks = phase.task.length; j < countTasks; j++) {
task = phase.task[j];
if (task.start < earliest) {
earliest = task.start;
}
if (task.end > latest) {
latest = task.end;
}
}
}
}
return { earliest: earliest, latest: latest };
}