2015-02-05 64 views
1

我正在嘗試改編Mike Bostock的泳道日曆http://bl.ocks.org/bunkat/1962173,並用JSON文件替換隨機數據生成函數。d3.js用異步函數替換random()數據函數

d3.json("random.json", function(data) { 
// console.log(d3.entries(data)); 
//var data = randomData() 
var lanes = data.lanes; 
var items = data.items; 
var now = new Date(); 
..... 
}); 

在數據文件看起來像隨機()函數的輸出:

{"lanes":[{"id":0,"label":"lane 0"},{"id":1,"label":"lane 1"},{"id":2,"label":"lane 2"},{"id":3,"label":"lane 3"},{"id":4,"label":"lane 4"}],"items":[{"id":0,"lane":0,"start":"2012-01-21T18:00:00.000Z","end":"2012-01-26T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":1,"lane":0,"start":"2012-01-28T18:00:00.000Z","end":"2012-02-02T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":2,"lane":0,"start":"2012-02-05T13:00:00.000Z","end":"2012-02-10T18:00:00.000Z","class":"past","desc":"This is a description."},{"id":3,"lane":0,"start":"2012-02-13T15:00:00.000Z","end":"2012-02-15T13:00:00.000Z","class":"past","desc":"This is a description."},{"id":4,"lane":0,"start":"2012-02-17T16:00:00.000Z","end":"2012-02-22T13:00:00.000Z","class":"past","desc":"This is a description."},{"id":5,"lane":0,"start":"2012-02-23T13:00:00.000Z","end":"2012-02-23T21:00:00.000Z","class":"past","desc":"This is a description."},{"id":6,"lane":0,"start":"2012-02-24T18:00:00.000Z","end":"2012-03-01T14:00:00.000Z","class":"past","desc":"This is a description."} 

我得到的錯誤是:

TypeError: n.getFullYear is not a function

回答

3

解析完JSON後,需要將字符串中的日期顯式轉換爲日期類型。

在給出的示例開始和結束變量創建爲日期通過您的項目迭代和轉換每個項目單獨

items.forEach(function(d){ 
    d.start = new Date(d.start); 
    d.end = new Date(d.end); 
}); 

D3對象

var dtS = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() + randomNumber(1,5), randomNumber(8, 16), 0, 0); 
var dateOffset = randomNumber(0,7); 
var dt = new Date(dtS.getFullYear(), dtS.getMonth(), dtS.getDate() + dateOffset, randomNumber(dateOffset === 0 ? dtS.getHours() + 2 : 8, 18), 0, 0); 

你可以做到這一點有一些幫手用於處理更復雜的日期字符串。你可以閱讀更多關於他們在這裏:https://github.com/mbostock/d3/wiki/Time-Formatting#parse

var parseDate = d3.time.format.iso.parse; 
items.forEach(function(d){ 
    d.start = parseDate (d.start); 
    d.end = parseDate (d.end); 
}); 
+0

這是great-我要看看我是否可以在陣列中替換日期的項目,而不是後期處理它們。 – user1515373 2015-02-06 14:29:29

+0

代替迭代項目,我用 替換了所有對'd.start'和'd.end'的引用d.start = new Date(d.start); 012.ec =新日期(d.end); 完美的作品! – user1515373 2015-02-06 14:49:43

1

我相信這是因爲在你的data.items你的startend屬性是字符串而不是日期(randomData()函數返回它們作爲日期)。

... 
var now = new Date(); 
items.forEach(function(d){ 
    d.start = new Date(d.start); 
    d.end = new Date(d.end); 
}); 
...