简体   繁体   中英

Iterating through the same dataset in Chart.js

I'm dealing with mixed chart using Chart.js Here is the code

var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
      label: 'Bar Dataset',
      data: [10, 20, 30, 40]
    }, {
      label: 'Line Dataset',
      data: [50, 50, 50, 50],

      // Changes this dataset to become a line
      type: 'line'
    }],
  labels: ['January', 'February', 'March', 'April']
  },
  options: options
  });

I need to iterate only the Line Dataset data instead of writing it four times something like this,

var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
      label: 'Bar Dataset',
      data: [10, 20, 30, 40]
    }, {
      label: 'Line Dataset',
      for(var i=0;i<4;i++){
      data: [50],
      }
      // Changes this dataset to become a line
      type: 'line'
    }],
 labels: ['January', 'February', 'March', 'April']
 },
 options: options
 });

As this is throwing some error Can u please help me in achieving this. Thank You

You can write a function for it:

... 
{
  label: 'Line Dataset',
  data: getLineData(50, 4),
  // Changes this dataset to become a line
  type: 'line'
}
... // end of chart options

function getLineData(value, times) {
  var data = []

  for(var i=0; i < times; i++) {
    data.push(value)
  }

  return data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM