2013-12-16 47 views
2

我試圖使用來自多個本地保存的json文件的數據構建高圖表條形圖,並且有點麻煩。爲了簡單起見,我想循環遍歷所有文件,搜索特定的字符串並使用count作爲我的圖的數據。我已經像這樣去了:如何從多個本地json文件生成高圖表

options.series[0].name = 'Test'; 
options.series[0].data = []; 

//Loop over the different local files and do a search count in each 
var localfiles = new Array('localfile1.json', 'localfile2.json'); 

for (var i=0; i<locfiles.length; i++) { 
    //do a count here 
    $.getJSON(localfiles[i], function(data) { 
    var count = 0; 
    var index = 0; 
    var entry; 
    for (index = 0; index < data.length; ++index) { 
     entry = data[index]; 
     if (entry.searchkey == "searchstring") { 
      count ++; 
     } 
     options.series[0].data.push(count); 
    }); 
}); 

var chart = new Highcharts.Chart(options); 

我意識到我沒有正確傳遞選項數組。但我不知道我應該怎樣編寫代碼。有什麼建議?

在此先感謝。

回答

1

拿到2條,你需要把options.series[0].data.push(count);第二循環外,否則你會與很多酒吧結束了長大

options.series[0].name = 'Test'; 
options.series[0].data = []; 

//Loop over the different local files and do a search count in each 
var localfiles = new Array('localfile1.json', 'localfile2.json'); 

for (var i=0; i<locfiles.length; i++) { 
    //do a count here 
    $.getJSON(localfiles[i], function(data) { 
    var count = 0; 
    var index = 0; 
    var entry; 
    for (index = 0; index < data.length; ++index) { 
     entry = data[index]; 
     if (entry.searchkey == "searchstring") { 
      count ++; 
     } 
    }); 
    options.series[0].data.push(count); 
}); 

var chart = new Highcharts.Chart(options); 

這種方式,您將獲得1條爲每個JSON文件

回答您的評論

可以使用addSeries

 var series1 = { 
         data: [], 
         name: "" 
        } 
    chart.addSeries(series1); 

如果你想刪除所有以前的系列,你可以做到這一點

while(chart.series.length > 0){ 
    chart.series[0].remove(true); 
} 
+0

嗨Moes。是的,我明白你的觀點(這是我的錯誤)。這裏我的問題是,在這個代碼的'選項'不再是範圍內的,因此我不能將計數推給它。 – GerryDevine

+0

你可以使用'addSeries'檢查答案 – Moes

+0

謝謝Moes,那就是我一直在尋找的東西。 – GerryDevine