Chartjs-Problem to create dynamic pie chart in ChartJS

0👍

The problem is that you wrap valores and etiquetas arrays in another array inside the config.

data: [ valores ]
labels: [ etiquetas ]

Just get rid of these sqare brackets and it will work.

data: valores
labels: etiquetas

Pleas have a look at the following runnable code snippet.

const response = [
  {"label":"assistingSales", "values":21},
  {"label":"hseMeeting", "values":12},
  {"label":"training", "values":30}
]

var valores   = new Array();
var etiquetas = new Array();

response.forEach(function(item){
  valores.push(item.values);
  etiquetas.push(item.label);
});

var config = {
  type: 'pie',
  data: {
    datasets: [{
      data: valores,
      backgroundColor: ['#FF6384', '#36A2EB','#FFCE56']
    }],
    labels: etiquetas
  },
  options: {
    responsive: true,
    legend: {
      position: 'top',
    },
    animation: {
      animateScale: true,
      animateRotate: true
    }
  }
};
new Chart(document.getElementById('myPieChart'), config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myPieChart"></canvas>

Leave a comment