在 chartjs 中分配折线图数据

assigning line chart data in chartjs

我有一个包含对象的数组,我想在 chartjs 中为折线图创建一个数据集,但是我得到的数据集是错误的,因此得到了两个折线图而不是一个。我在这里做错了什么?

const data = [{May 04: '', May 05: '1', May 06: ''}, {May 04: '2', May 05: '', May 06: ''}]

const chartData = {
          labels: ['May 04', 'May 05', 'May 06' ]
          datasets: getDataSet(data),
        };

const getDataSet = (data) => {
  const dataSet = [];


  dataSet.push({ label: 'Total' });
  data.forEach((v) => {
  dataSet.push({
    data: Object.values(v),
  });
})
  return dataSet;
};

您的问题可以通过以下代码解决:

const data = [
  { 'May 04': '', 'May 05': '1', 'May 06': ''},
  { 'May 04': '2', 'May 05': '', 'May 06': ''}
];

const getDataSet = data => {  
  const dsData = [0, 0, 0];
  data.forEach(o => Object.values(o).forEach((v, i) => dsData[i]+= Number(v)));
  return { 
    label: 'Total', 
    data: dsData
  };
};

const chartData = {
  labels: ['May 04', 'May 05', 'May 06'],
  datasets: [getDataSet(data)]
};

console.log(chartData);

如果您的数据是动态的,可以按如下方式完成:

const data = [
  { 'May 04': '', 'May 05': '1', 'May 06': '', 'May 07': '1' },
  { 'May 04': '2', 'May 05': '', 'May 06': '', 'May 07': '2' }
];

const getDataSet = data => {  
  const dsData = Object.keys(data[0]).fill(0);
  data.forEach(o => Object.values(o).forEach((v, i) => dsData[i]+= Number(v)));
  return { 
    label: 'Total', 
    data: dsData
  };
};

const chartData = {
  labels: Object.keys(data[0]),
  datasets: [getDataSet(data)]
};

console.log(chartData);

const data = [
  { 'May 04': '', 'May 05': '1', 'May 06': '', 'May 07': '1' },
  { 'May 04': '2', 'May 05': '', 'May 06': '', 'May 07': '2' }
];

const getDataSet = data => {  
  const dsData = Object.keys(data[0]).fill(0);
  data.forEach(o => Object.values(o).forEach((v, i) => dsData[i]+= Number(v)));
  return { 
    label: 'Total', 
    data: dsData
  };
};

const chartData = {
  labels: Object.keys(data[0]),
  datasets: [getDataSet(data)]
};

new Chart('myChart', {
  type: 'line',
  data: chartData,
  options: {
    scales: {
      y: {
        ticks: {
          stepSize: 1
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>