Chartjs-Chart.JS Get Json data for chart and return dataset where a type equals a certain type

0👍

I understand that you’re looking for a way to transform the JSON result into datasets of a format that can be interpreted by Chart.js.

You could first extract unique labels from jsonresult using Array.reduce()

const labels = jsonresult.result.reduce((acc, o) => acc.includes(o.Types) ? acc : acc.concat(o.Types), []);

Then you can create the datasets as shown below. Note that bgColors and borderColors are arrays the need to contain at least as many color definition as the number of expected datasets.

const datasets = labels.map((l, i) => ({
  label: l,
  data: jsonresult.result.filter(o => o.Types == l).map(o => o.Total),
  fill: false,
  backgroundColor: bgColors[i],  
  borderColor: borderColors[i],
  ...
}));

Please take a look at your amended code and see how it works.

const jsonresult = {
  result: [
    {Types: "Parts Order", Total: 5100},
    {Types: "Parts Order", Total: 4230},
    {Types: "Parts Order", Total: 5990},
    {Types: "Service", Total: 13530},
    {Types: "Service", Total: 14380},
    {Types: "Service", Total: 15390}
  ]
};

const labels = jsonresult.result.reduce((acc, o) => acc.includes(o.Types) ? acc : acc.concat(o.Types), []);
const datasets = labels.map((l, i) => ({
  label: l,
  data: jsonresult.result.filter(o => o.Types == l).map(o => o.Total),
  fill: false,
  backgroundColor: ['rgba(210, 214, 222, 0.6)', 'rgba(60,141,188, 0.6)'][i],  
  borderColor: ['rgb(210, 214, 222)', 'rgb(60,141,188)'][i],
  pointHoverBackgroundColor: '#fff',
  pointHoverBorderColor: ['rgb(220,220,220)', 'rgb(60,141,188)'][i], 
  borderWidth: 1
}));

new Chart('monthlySalesChart', {
  type: 'line',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    datasets: datasets,
  },
  options: {
    scales: {
      xAxes: [{
        gridLines: {
          display: false
        }
      }],
      yAxes: [{
        ticks: {
          min: 200,
          max: 100000,
          stepSize: 20000,
          callback: v => '$' + v.toString().split(/(?=(?:...)*$)/).join(',') + '.00'
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="monthlySalesChart" height="80"></canvas>

Leave a comment