score:60

Accepted answer

Your approach on constructing the chart is completely inappropriate. Here is the proper way, that you should follow :

var jsonfile = {
   "jsonarray": [{
      "name": "Joe",
      "age": 12
   }, {
      "name": "Tom",
      "age": 14
   }]
};

var labels = jsonfile.jsonarray.map(function(e) {
   return e.name;
});
var data = jsonfile.jsonarray.map(function(e) {
   return e.age;
});;

var ctx = canvas.getContext('2d');
var config = {
   type: 'line',
   data: {
      labels: labels,
      datasets: [{
         label: 'Graph Line',
         data: data,
         backgroundColor: 'rgba(0, 119, 204, 0.3)'
      }]
   }
};

var chart = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>

score:0

I found the solution proposed by Bear GRiZZLY XI quite helpful. Makes use of the for.. loop.

Let's suppose you have a json response from your api as follows:

var markschart = document.getElementbyId("markschart");

{
    "labels": "Maths,Geography,Physics,Chemistry,English,Biology,Music",
    "datasets": [
        {
            "label": "Student 3",
            "data": "120, 90, 45, 90, 14, 100, 88",
            "spanGaps": false
        },
        {
            "label": "Student 2",
            "data": "150, 80, 99, 100, 90, 110, 97",
            "spanGaps": false
        },
        {
            "label": "Student 1",
            "data": "140, 100, 89, 134, 120, 78, 56",
            "spanGaps": false
        }
    ]
}

in javascript you may handle the response as follows (response contains the above json packet):

var mydatasets = [];
var colorslist = ["blue","orange","magenta","green","syrup","navy","bumblebee","turkish","army","ferrari"];

for(var j = 0; j < response.datasets.length; j++) {
  mydatasets.push({label: response.datasets[j].label, boderColor: colorslist[j], data: response.datasets[j].data.splits(','), spanGraphs: true});
}
var subjectsData = {
  labels: response.labels.split(','),
  datasets: mydatasets
}

var options = {
  scales: { 
   yAxes: [{
      ticks: {
             beginAtZero: true
           },
      scaleLabel: {
             display: true,
             labelString: 'Subject Perfomance',
             fontSize: 14
           }
  }]
 }
};

var studentsMarksPerformance = new Chart(markschart, {
      type: "line",
      data: subjectsData ,
      options: options
});

The above is not a complete solution but may help with implementing for..each loop in creating a line chart using Chart.js


More Query from same tag