1👍
✅
Given the data is available in the variable health
, you can extract the labels
through Object.keys()
as follows.
labels: Object.keys(health),
The data
of individual datasets can be extracted through Object.values()
, followed by Array.map()
. The data of the first dataset for example is defined as follows.
data: Object.values(health).map(v => v[0]),
Please have a look at your amended and runnable code below.
const health = {
"2020": [1, 2, 3],
"2021": [4, 5, 6]
}
var myLineChart = new Chart('myChart', {
type: 'line',
data: {
labels: Object.keys(health),
datasets: [{
label: "Pass",
data: Object.values(health).map(v => v[0]),
backgroundColor: 'rgba(71,193,28, 0.71)',
borderColor: 'rgb(71,193,28)',
fill: false
},
{
label: "Failed",
data: Object.values(health).map(v => v[1]),
backgroundColor: 'rgba(212,0,13,0.71)',
borderColor: 'rgb(212,0,13)',
fill: false
},
{
label: "Skipped",
data: Object.values(health).map(v => v[2]),
backgroundColor: 'rgba(228,78,231,0.56)',
borderColor: 'rgb(228,78,231)',
fill: false
}
]
},
options: {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>
Source:stackexchange.com