Chartjs-Pass List of Objects as data

0👍

You’ll find an example on ChartJS’s site. If you open the source (Ctrl+U), you’ll see how they declare the options. Something along these lines:

const data = [{someID:"1111",otherID:"9999",name:"SomeName",aTotal:"32",bTotal:"16000",cTotal:"800",rank:"1",lastactivity:"44 h",timestamp:"0"},{someID:"01234",otherID:"9876",name:"SomeName",aTotal:"63",bTotal:"2300",cTotal:"950",rank:"2",lastactivity:"12.11.",timestamp:"0"}];
const ctx = document.getElementById("myChart").getContext("2d");

const cfg = {
  type: "bar",
  data: {
    labels: data.map(({someID, name}) => `${name} (${someID})`),
    datasets: [{
        label: 'aTotal',
        backgroundColor: 'rgba(255, 99, 132, 0.5)',
        data: data.map(({aTotal}) => aTotal),
      },
      {
        label: 'bTotal',
        backgroundColor: 'rgba(54, 162, 235, 0.5)',
        data: data.map(({bTotal}) => bTotal),
      },
      {
        label: 'cTotal',
        backgroundColor: 'rgba(75, 192, 192, 0.5)',
        data: data.map(({cTotal}) => cTotal),
      },
    ],
  },
};

const myChart = new Chart(ctx, cfg);
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script>
<canvas id="myChart" width="400" height="110"></canvas>

Leave a comment