[英]How to add new dataset in line chart of chart.js by iterating over dictionary in JavaScript?
我正在尝试从charts.js 中显示折线图,它在图中显示通过、失败和跳过的测试用例结果。 在这里,我对数据集中的数据数量进行了硬编码。 我想通过遍历 object 来添加数据点。 Object 看起来像这样
var temp = {"2020":[1,2,3],
"2021":[4,5,6]}
下面是我的 javascript function 折线图。
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
}
});
}
鉴于变量health
中的数据可用,您可以通过Object.keys()
提取labels
,如下所示。
labels: Object.keys(health),
可以通过Object.values()
提取单个数据集的data
,然后是Array.map()
。 例如,第一数据集的数据定义如下。
data: Object.values(health).map(v => v[0]),
请在下面查看您修改后的可运行代码。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.