Chartjs-Iterating over an array of objects and stack a Chart JS Bar?

1👍

Given your backend data present in an array named baseData, you could use the Array.map() and Object.values() methods in order to generate the datasets as follows:

const colors = ['green', 'red'];
const datasets = baseData.map((o, i) => ({
  label: o.user.username,
  data: Object.values(o.hours),
  backgroundColor: colors[i]
}));

Please take a look at your amended code below:

const baseData = [{
    "user": {
      "username": "erik",
      "first_name": "erik",
      "email": "erik@admin.com"
    },
    "hours": {
      "day_1": 13.0,
      "day_2": 14.0,
      "day_3": 9.0,
      "day_4": 8.0,
      "day_5": 8.0,
      "day_6": 3.0,
      "day_7": null
    },
    "project": 21,
    "year": 2020,
    "week": 37
  },
  {
    "user": {
      "username": "mega",
      "first_name": "boy",
      "email": "mega@boy.com"
    },
    "hours": {
      "day_1": 5.0,
      "day_2": 10.0,
      "day_3": 8.0,
      "day_4": 8.0,
      "day_5": null,
      "day_6": null,
      "day_7": null
    },
    "project": 21,
    "year": 2020,
    "week": 37
  }
];

const colors = ['green', 'red'];
const datasets = baseData.map((o, i) => ({
  label: o.user.username,
  data: Object.values(o.hours),
  backgroundColor: colors[i]
}));

new Chart('canvas', {
  type: 'bar',
  data: {
    labels: ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
    datasets: datasets
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: 'Weekly Summary'
    },
    scales: {
      yAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        stacked: true
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas"></canvas>

Leave a comment