0👍
So it was my json, what I ended up doing was passing the full list of rounds to my javascript, then inside the thymeleaf loop I passed the roundId via the th:roundId.
html
inside the thymeleaf loop
<div class="container-fluid">
<canvas th:roundId="${round.roundId}" th:id="myChart"></canvas>
</div>
passing the full list of rounds
<script th:inline="javascript">
let rounds = /*[[${roundsJsonNode}]]*/ {};
</script>
then in the javascript I get the round by id using the getRoundsById method, and create a bar chart for each round.
function getRoundById(rounds, roundId) {
return rounds.find((round) => round.roundId === Number(roundId));
}
const charts = document.querySelectorAll('[roundId]');
charts.forEach(chart => {
const getRound = chart.getAttribute('roundId').split(',');
const roundData = getRoundById(rounds, getRound);
const scoreCount = roundData.scores.length;
const scoreData = {};
for (let i = 0; i < scoreCount; i++) {
const score = roundData.scores[i];
if (!scoreData[score.name]) {
scoreData[score.name] = {
count: 0,
color: score.color,
score: score.score,
};
}
scoreData[score.name].count += 1;
}
const datasets = [];
Object.entries(scoreData).forEach(([name, data]) => {
datasets.push({
label: name,
backgroundColor: data.color,
data: [data.count],
score: data.score, // add score value to dataset object
});
});
datasets.sort((a, b) => a.score - b.score); // sort datasets by score value
const myChart = new Chart(chart, {
type: 'bar',
options: {
responsive: true,
maintainAspectRatio: false,
indexAxis: 'y',
scales: {
x: {
stacked: true,
display: false,
},
y: {
stacked: true,
display: false,
},
},
plugins: {
legend: {
display: false,
},
},
},
data: {
labels: [''],
datasets,
},
});
});
- Chartjs-Chartjs show seconds on the x axis and volume on the y
- Chartjs-Links in bar charts (charts.js)
Source:stackexchange.com