I am trying to display linechart from charts.js where it shows the pass,fail and skipped test case reults in graph. Here i have hardcoded the number of data in a dataset. I want to add the datapoints by iterating through the object. Object looks like this
var temp = {"2020":[1,2,3],
"2021":[4,5,6]}
And my javascript function for line chart below.
function GetHealthReport(health,id) {
console.log(health);
var Date = Object.keys(health);
var ctxL = document.getElementById(id).getContext('2d');
var myLineChart = new Chart(ctxL, {
type: 'line',
data: {
labels: Date,
datasets: [
{
label:"Pass",
data: [health[Date[0]][0],health[Date[1]][0],health[Date[2]][0],health[Date[3]][0],health[Date[4]][0]],
backgroundColor: [
'rgba(71,193,28,0.71)'
]
},
{
label:"Failed",
data: [health[Date[0]][1],health[Date[1]][1],health[Date[2]][1],health[Date[3]][1],health[Date[4]][1]],
backgroundColor: [
'rgba(212,0,13,0.71)'
]
},
{
label:"Skipped",
data: [health[Date[0]][2],health[Date[1]][2],health[Date[2]][2],health[Date[3]][2],health[Date[4]][2]],
backgroundColor: [
'rgba(228,78,231,0.56)'
]
}
]
},
options: {
responsive: true
}
});
}
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.