Chartjs-Chart.js data forming though the API dynamically based on selects

0πŸ‘

the first step is to create individual datasets(arrays) for β€œdate”,”6β€³ and β€œ0”.you can use the map function in javascript to create these datasets.for example,if the API data is stored in a variable called obj then,

 labels=obj.map(function(e) {
  return e["date"];
  })     

the labels will have the date information,then for the β€œ6”,”0β€³

var data1={
label:"6",
data: obj.map(function(e) {
 return e["6"]
 },
backgroundColor:"red"

}

data1 will conatin the data from β€œ6”;NOTE:the data from β€œ6” is in string format,inorder to use it in the chart you need to parse the value into float or integer before returning in the above step.and similarly for β€œ0”(ie., data2).the color attribute is also added above. if you need both data1 and data2 in the same chart,then create a combined dataset like this

    data={data1,data2}

then create the chart by providing the above values

new Chart(document.getElementById("myChart"), {
  type: 'bar',
  data: {
  labels:labels,
  datasets:data
  }
 }

this is simplest example i could come up with,Hope it helps

Leave a comment