Chartjs-Chart.js – How to parse array of objects as the dataset for Pie Chart

2πŸ‘

βœ…

From the Pie Chart Data Structure docs, it mentions that:

datasets need to contain an array of data points. The data points should be a number,

You need to follow its structure as below:

public pieChartDatasets = [
  {
    data: [300, 500, 100],
  },
];

labels = [
    'Red',
    'Yellow',
    'Blue'
];

Well, you can transform your chartData to match its structure:

pieChartLabels: string[] = [];
pieChartDatasets: any[] = [];

this.pieChartLabels = this.chartData.map((x) => x.label);
this.pieChartDatasets = [
  {
    data: this.chartData.map((x) => x.data),
  },
];

And in the baseChart HTML element, pass the pieChartLabels to [labels] attribute.

<canvas
  baseChart
  [datasets]="pieChartDatasets"
  [type]="pieChartType"
  [options]="pieChartOptions"
  [labels]="pieChartLabels"
>
</canvas>

Demo (CustomPieComponent) @ StackBlitz

Leave a comment