I am new to Chart.js and also not very experience at writing javascript generally. I currently have hacked together a 4-line chart but I’d like to make the code a bit more dynamic so that if the incoming data changes (say for example a 5th category was present) that the JS code would be able to pick that up without having to re-write it.
chart.js code & html
const ctx = document.getElementById('myChart');
const data = JSONinput;
new Chart(
ctx,
{
type: 'line',
data: {
labels: data.map(row => row.DataPoints.map(p => p.LogDate))[0],
datasets: [
{
label: data.map(row => row.Name)[0],
data: data.map(row => row.DataPoints)[0].map(k => k.Score)
},
{
label: data.map(row => row.Name)[1],
data: data.map(row => row.DataPoints)[1].map(k => k.Score)
},
{
label: data.map(row => row.Name)[2],
data: data.map(row => row.DataPoints)[2].map(k => k.Score)
},
{
label: data.map(row => row.Name)[3],
data: data.map(row => row.DataPoints)[3].map(k => k.Score)
}
]
}
};
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
JSON input
[
{
"Name": "Red",
"DataPoints": [
{
"LogDate": "2023-02-19T13:07:13.643",
"Score": 478.5
},
{
"LogDate": "2023-03-01T23:13:04.45",
"Score": 594.0
}
]
},
{
"Name": "Blue",
"DataPoints": [
{
"LogDate": "2023-02-19T13:07:13.643",
"Score": 546.5
},
{
"LogDate": "2023-03-01T23:13:04.45",
"Score": 657.0
}
]
},
{
"Name": "Green",
"DataPoints": [
{
"LogDate": "2023-02-19T13:07:13.643",
"Score": 687.0
},
{
"LogDate": "2023-03-01T23:13:04.45",
"Score": 757.0
}
]
},
{
"Name": "Purple",
"DataPoints": [
{
"LogDate": "2023-02-19T13:07:13.643",
"Score": 518.0
},
{
"LogDate": "2023-03-01T23:13:04.45",
"Score": 668.0
}
]
}
]
Also if there’s a way of shortening the datetime so that it only displays the date component then that’d be great too, thanks.
>Solution :
Assuming your data is as long as you want your dataset is, you can do something like this;
const ctx = document.getElementById('myChart');
const data = JSONinput;
const datasets = data.map(row => ({
label: row.Name,
data: row.DataPoints.map(k => k.Score)
}));
new Chart(
ctx,
{
type: 'line',
data: {
// The map on this line was not necessary
labels: data[0].DataPoints.map(p => p.LogDate),
datasets
}
});
Data passed into the chart ends up looking like this:
{
"type":"line",
"data":{
"labels":[
"2023-02-19T13:07:13.643",
"2023-03-01T23:13:04.45"
],
"datasets":[
{
"label":"Red",
"data":[
478.5,
594
]
},
{
"label":"Blue",
"data":[
546.5,
657
]
},
{
"label":"Green",
"data":[
687,
757
]
},
{
"label":"Purple",
"data":[
518,
668
]
}
]
}
}