Chartjs-How to populate data in chart.js

2👍

just map the key and values to appropriate arrays and consume them as datasets and labels.

var data = {
  "count": 2,
  "result": {
    "2020-01-22": {
      "confirmed": 12,
      "deaths": 5,
      "recovered": 4
    },
    "2020-01-23": {
      "confirmed": 20,
      "deaths": 3,
      "recovered": 2
    }
  }
}
var dates = Object.keys(data["result"]).map(x => x);
var confirm = Object.values(data.result).map(x => x.confirmed);
var deaths = Object.values(data.result).map(x => x.deaths);
var recovered = Object.values(data.result).map(x => x.recovered);


var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: dates,
    datasets: [{
        label: 'confirmed',
        data: confirm,
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgba(255, 99, 132, 1)',
        borderWidth: 1
      },
      {
        label: 'Deaths',
        data: deaths,
        backgroundColor: 'rgba(54, 162, 235, 0.2)',


        borderColor: 'rgba(54, 162, 235, 1)',

        borderWidth: 1
      }, {
        label: 'recovered',
        data: recovered,
        backgroundColor: 'rgba(255, 206, 86, 0.2)',


        borderColor: 'rgba(255, 206, 86, 1)',

        borderWidth: 1
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" width="100" height="50"></canvas>

Leave a comment