Display JSON data in chartjs

๐Ÿ‘:0

You need to do something like this this

Try to read your data like this:

var dates = [];
var allTeamMember = [];

getHistoricalData().forEach(function(element, index, array) {
  dates.push(element.date);
  var teamMember = []
  element.results.forEach(function(element, index, array) {
    var questions = [];
    element.questions.forEach(function(element, index, array) {
        questions.push(element.value);
    });
    teamMember[element.teamMemberId] = questions;
  });
  allTeamMember.push(teamMember);
});

This gives you an array with all the dates. And also an array having an inner array for each date containing all teamMembers with their question values.

After having this data you can generate charts from it like this:

dates.forEach(function(element, index, array) {


$("#charts").append("<canvas id=\"chart-" + index + "\" width=\"400\" height=\"400\"></canvas>");
  var ctx = $("#chart-" + index);
  var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [1,2,3],
        datasets: [{
            label: 'Datum: ' + dates[index],
            data: allTeamMember[index][getKeys(allTeamMember[index])[0]],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});


});

function getKeys(obj, filter) {
    var name,
        result = [];

    for (name in obj) {
        if ((!filter || filter.test(name)) && obj.hasOwnProperty(name)) {
            result[result.length] = name;
        }
    }
    return result;
}

you would need to not always take index zero like I do but iterate over your teamMembers.

Hope that helps. Just try to do it yourself.

Leave a comment