Search code examples
javascriptreactjschart.jsreact-chartjsreact-chartjs-2

Map through datasets in chartjs


I have this static dataset's data ranging from 2015 to 2016 and I want to map everything out instead of manually adding the bars myself.

final_water_supply Data image representation

var ctx = document.getElementById('mc').getContext('2d');

chartRef1 = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: sortedData,
                datasets: [{
                        label: '2015',
                        stack: 'Stack 1',
                        data: final_water_supply[0],
                        backgroundColor: '#D0D1E6',
                        borderColor: '#D0D1E6',
                    },
                    {
                        label: '2016',
                        stack: 'Stack 2',
                        data: final_water_supply[1],
                        backgroundColor: '#74A9CF',
                        borderColor: '#74A9CF',
                    },
                    {
                        label: '2017',
                        stack: 'Stack 3',
                        data: final_water_supply[2],
                        backgroundColor: '#0570B0',
                        borderColor: '#0570B0',
                    },
                    {
                        label: '2018',
                        stack: 'Stack 4',
                        data: final_water_supply[3],
                        backgroundColor: '#023858',
                        borderColor: '#023858',
                    }
                ]
            },

Solution

  • So this is how I ended up doing it

    created an empty object structure that takes in the datasets

             let color = '#d6d6d6'
             let data = {
                labels:sortedData,
                datasets:[]
                }
    

    crated a forEach function that loops through the years and push in data into the datasets

              years.forEach(function(a,i) {
                switch(i) {
                  case 0:
                    color='#D0D1E6'
                    break;
                  case 1:
                    color='#74A9CF'
                    break;
                  case 2:
                    color='#0570B0'
                    break;
                  case 3:
                    color='#023858'
                    break;
                  default:
                    color='#d6d6d6'
                }
                    data.datasets.push({
                    label: a,
                    stack: 'Stack '+i,
                    data: final_water_supply[i],
                    backgroundColor: color,
                    borderColor: color,
                  })
                })