score:5

Accepted answer

there is no built-in way to create your chart using an array straight into the data.

but you can create a small work around using chart.js plugins. they let you handle events triggered during the whole creation of the chart, such as before it is initialized, after a resize, etc.


follows a small plugin that will populate all the data for you using an array :

var myplugin = {
    // we edit what is happening before the chart is initialized.
    beforeinit: function(chart) {
        var data = chart.config.data;

        // `apiarray` is what you get from your api.
        // for every data in this array ...
        for (var i = 0; i < apiarray.length; i++) {
            // populate the labels array with the first value ..
            data.labels.push(apiarray[i][0]);
            // .. and the data with the second value
            data.datasets[0].data.push(apiarray[i][1]);
        }
    }
};

then you need to add this newly created plugin to your chart plugin services :

chart.pluginservice.register(myplugin);


make sure to register the plugin before creating the chart (before calling new chart()), or else it won't work.
i also suggest to have an empty data in your chart (before the plugin occurs) to make sure you won't have data you don't want.

you can see a fully working example on this jsfiddle.


Related Query

More Query from same tag