I'm using Chart.JS to make a bar chart, but I'm having issues using two JSON objects that I created to make the chart dynamic. I'm not sure of how I should do this but the objects can change values and I want to make the chart support that.
This is my object for labels:
0: {labelName: "Plan Miles"}
1: {labelName: "Actual Miles"}
2: {labelName: "Route Variance"}
and I have a similar object for my data sets.
The object values can be any number so I want to make my chart dynamic to support that.
What can I change in my code to make that happen?
I want to remove the second and third datapoint and only have one dataset that will support multiple bars in the chart. So I would like to loop or map through both the label JSON object and data JSON object to make the chart.
charts.component.ts
export class ChartsComponent implements OnInit {
canvas: any;
ctx: any;
ChartData: any;
labelNames: any;
constructor() {}
ngOnInit(): void {
// Charts
this.canvas = document.getElementById('viewChart');
this.ctx = this.canvas.getContext('2d');
this.ChartData = JSON.parse(localStorage.getItem('ChartData'));
const data = this.ChartData;
//Label Object for Chart
this.labelNames = JSON.parse(localStorage.getItem('LabelNames'));
const labelNames = this.labelNames;
const labelObject = [];
// tslint:disable-next-line: prefer-for-of
for(let i = 0; i < labelNames.length; i++) {
const obj = labelNames[i].propertyName;
labelObject.push({labelName: obj});
}
const newLabelObject = labelObject.slice(3, 5 + 1)
console.log('Labels: ', newLabelObject);
// tslint:disable-next-line: only-arrow-functions
const barLabel = newLabelObject.map(function (e) {
return e[1];
})
// tslint:disable-next-line: only-arrow-functions
const driverLabel = data.map(function (e: any[]) {
return e[1];
});
// tslint:disable-next-line: only-arrow-functions
const firstDataPoint = data.map(function (e: any[]) {
return e[3];
});
// tslint:disable-next-line: only-arrow-functions
const secondDataPoint = data.map(function (e: any[]) {
return e[4];
});
// tslint:disable-next-line: only-arrow-functions
const thirdDataPoint = data.map(function (e: any[]) {
return e[5];
});
const viewChart = new Chart(this.ctx, {
type: 'bar',
data: {
labels: driverLabel,
datasets: [
{
label: `newLabelObject`,
data: firstDataPoint,
backgroundColor: 'rgb(34, 167, 240)',
borderWidth: 1
},
{
label: 'Actual Miles',
data: secondDataPoint,
backgroundColor: 'rgb(240, 52, 52)',
borderWidth: 1
},
{
label: 'Route Variance',
data: thirdDataPoint,
backgroundColor: 'rgba(254, 241, 96, 1)',
borderWidth: 1
}
]
},