Chartjs-Loop through array for chart.js input

1👍

You don’t need any loop here you just need to get value from particular index of createObject ,But since the chartObject is object so you need to make a copy while passing data to have immutability so you can use ... or slice or map to have a copy

You can simply use ... spread syntax,

data : {
  labels : [...chartObject[0]],
  datasets: [{
    label: 'frequency',
    data: [...chartObject[1]],
    ...
  }]
}

If you’re sure the value being passed to Chart will not mutate the original state, you can directly pass them as

data : {
  labels : chartObject[0],
  datasets: [{
    label: 'frequency',
    data: chartObject[1],
    ...
  }]
}

1👍

You can use Array.prototype.map :

labels: chartObject[0].map((x, i) => chartObject[0][i]), 
datasets: [{
    label: "Frequency",
    data: chartObject[1].map((x, i) => chartObject[1][i])
}]

Leave a comment