22

I am trying to use Chart JS to create a table with dynamically generated data points coming from my JSON file. The logic of my code looks like so:

var datapart;
for (i = 0; i < jsonfile.jsonarray.length; i++){
     datapart += {
          label: jsonfile.jsonarray[i].name,
          data: [jsonfile.jsonarray[i].age] 
     };
}

var config = {
   type: 'line',
   data: {
      labels: ["Graph Line"],
      datasets: [datapart]
   }
}

My JSON file meanwhile looks something like so:

{
"jsonarray": [
    {
      "name": "Joe",
      "age": 12
    },
    {
      "name": "Tom",
      "age": 14
    }
]
}

The config variable houses the configuration settings for ChartJS, including setting datapoints. When loaded into ChartJS, config provides information needed to display my chart.

Anyhow, my thinking was to use the variable datapart as a means of appending the datasets using my for loop. Unfortunately the code produces no results. I understand that my method for appending variables is faulty, but am unsure how to proceed.

How might I go about adding these JSON values to Chart.js?

2 Answers 2

67

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>

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

6 Comments

Thanks! A much better way of including my data. The only issue I am having now is that this prints as one dataset, when I would like both people in my list to be separated into their own dataset.
Are you sure? Cause that would look something like this. This^^ is the general way.
Yes, that's the format I'm more going for. Only I am trying to figure out how to make each dataset dynamically, depending on the people on my list.
Got it figured out! Basically took cues from this answer stackoverflow.com/questions/26397009/…
One thing about this approach is that you end up looping over the data twice. More efficient to do it in one for loop
|
1

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

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.