1

I have a problem with parsing data to my chart. For sure, this should be included in an automatic process I use getJSON and don't want to use ajax, so I have:

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

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

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

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

        console.log(labels)
        console.log(data)
    });

So of course labels and data are logged to console in a proper way e.g.:

(5) [1,2,3,4,5]

But how to use it in this part:

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)',
            }]
        },
    });

Because index.html generates an empty chart without data. How to map labels and data in the proper way?

1
  • Firstly $.getJSON is an async call and labels and data are local variables. Those variables are undefined out of the scope of your callback function. Commented Mar 21, 2019 at 11:11

1 Answer 1

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)',
            }]
        },
    });

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.