[Chartjs]-Mapping data (from getJSON response) in Chart.js

3👍

labels and data variables are undefined outside of your $.getJSON‘s done callback function.

You can call a function in done i.e createChart(labels, data) or can bring you chart code inside done

$.getJSON('file.json').done( function (results) {  

        var labels = [];
        var data = [];

        var labels = results.map(function (item) {
            return item.updatedLabels
        });

        var data = results.map(function (item) {
            return item.updatedData;
        });

        // Create chart
        createChart(labels, data);

});
function createChart(labels, data) {
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Example',
                data: data,
                borderColor: 'rgba(75, 192, 192, 1)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
            }]
        },
    });

}

Leave a comment