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