[Chartjs]-Parsing data on chartJS Horizontal

1👍

Instead of defining parsing.yAxisKey, you could map the raw data as follows:

data: rawData.map(o => o.products.sales),

Please take a look at your amended and runnable code below and see how it works.

const labels = ['s', 'a', 'd'];
const rawData = [
  {products: { sales: [0, 5], id: 1 } },
  {products: { sales: [5, 10], id: 2 } },
  {products: { sales: [10, 15], id: 3 } },
];

const data = {
  labels: labels,
  datasets: [{
    label: 'Weekly Sales',
    data: rawData.map(o => o.products.sales),
    backgroundColor: [
      'rgba(255, 26, 104, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(255, 206, 86, 0.2)',
    ],
    borderColor: [
      'rgba(255, 26, 104, 1)',
      'rgba(54, 162, 235, 1)',
      'rgba(255, 206, 86, 1)',
    ],
    borderWidth: 1
  }]
};

// config 
const config = {
  type: 'bar',
  data,
  options: {    
    indexAxis: 'y',
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
};

new Chart('myChart', config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Leave a comment