1👍
✅
instead of sending each count to the function and hardcoding the list of emotions in chart, you can try doing following
Create object containing all possible emotions with initial default value as 0.
const emotions = {
angry: 0,
disgusted: 0,
fearful: 0,
happy: 0,
neutral: 0,
sad: 0,
surprised: 0
}
your response from AJAX looks something like this right,
const response = [
{emotion_state: 'angry', CountOf: '34'},
{emotion_state: 'disgusted', CountOf: '3'},
{emotion_state: 'fearful', CountOf: 0},
.
.
]
after the ajax response you can update your emotions
object with count like below
for (const item of response) {
if (emotions.hasOwnProperty(item.emotion_state)) {
emotions[item.emotion_state] = item.CountOf
}
}
then pass it to the graph function like below
generategraph(Object.entries(emotions))
and then update your function to handle your inputs like
function generategraph(input){
if(myChart!=null)
{
myChart.destroy();
}
myChart = new Chart (ctx, {
type: 'bar',
data: {
labels: input.map(i => i[0].charAt(0).toUpperCase() + i[0].slice(1)),
datasets: [{
label: '# of Votes',
data: input.map(i => i[1]),
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
Source:stackexchange.com