How to generate highcharts chart from multiple local json files

天大地大妈咪最大 提交于 2019-12-24 03:49:35

问题


I'm trying to construct a highcharts barchart using data from multiple locally held json files and having a bit of trouble. For simplicity's sake I want to loop through all files, do a search for a particular string and use the count as the data for my graph. I've went about it like so:

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);

I realise that I'm not passing the options array around correctly. But I'm not sure what way I should code this. Any advice?

Thanks in advance.


回答1:


to get 2 bars you need to put the options.series[0].data.push(count); outside the second loop otherwise you gonna end up with lots of bars growing up

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);

this way you'll get 1 bar for each json file

to answer your comment

you can use addSeries

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

if you want to remove all previous series you can do that

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


来源:https://stackoverflow.com/questions/20603104/how-to-generate-highcharts-chart-from-multiple-local-json-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!