[Chartjs]-How to create a chart with chartjs.org with data from an array?

1👍

You can map your array of objects, getting only the value you need.
I did it by
var values = myArray.map((x) => x.value)
and then using values as the value to the data property inside chart options.

For the labels, you can use the same logic, but with x.year.

Below code represents an example:

var myArray = [{
    year: '2016',
    value: 5
  },
  {
    year: '2017',
    value: 9
  },
  {
    year: '2018',
    value: 4
  }
];

//FILTER THE VALUES
var values = myArray.map((x) => x.value)

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['2016', '2017', '2018'],
    datasets: [{
      label: '# of Votes',
      data: values,
      borderWidth: 1,
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)'
      ],
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart" width="300" height="150"></canvas>

If, for some reason (browser maybe), you cant use arrow functions, then go with:
var values = myArray.map(function(x) {return x.value})

Leave a comment