How to generate highcharts chart from multiple loc

2019-07-18 09:26发布

问题:

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