Chartjs-Moving Data To Object Within Array

1👍

You need to set some variables and use those instead of hardcoding data….

So…..

// Canvas element exists after this line.
resultsContainer.innerHTML = displayResults;

// Now the myChart element is in the DOM, select it.
let myChart = document.getElementById('myChart').getContext('2d');

// Create a new chart.
let chartResults = new Chart(myChart, {
    type: 'bar',
    data: {
        labels: [ 'Year 1', 'Year 2', 'Year 3', 'Year 4', 'Year 5', 'Year 6', 'Year 8', 'Year 9', 'Year 10' ],
        datasets: [
            {
                label: 'Savings Per Year £',
                data: [ 342, 410, 443, 501, 557, 602, 673, 702, 764, 823 ],
                backgroundColor: '#168ecf'
            }
        ]
    },
    options: {}
});

becomes something like…..

var savingsperyear = [ 342, 410, 443, 501, 557, 602, 673, 702, 764, 823 ];
// Canvas element exists after this line.
resultsContainer.innerHTML = displayResults;

// Now the myChart element is in the DOM, select it.
let myChart = document.getElementById('myChart').getContext('2d');

// Create a new chart.
let chartResults = new Chart(myChart, {
    type: 'bar',
    data: {
        labels: [ 'Year 1', 'Year 2', 'Year 3', 'Year 4', 'Year 5', 'Year 6', 'Year 8', 'Year 9', 'Year 10' ],
        datasets: [
            {
                label: 'Savings Per Year £',
                data: savingsperyear,
                backgroundColor: '#168ecf'
            }
        ]
    },
    options: {}
});

(that keeps the data on load of the page…)

Then, to update it, in your calc function

yearOneSaving = totalSaving * 12 * 0.03;
yearTwoSaving = totalSaving * 12 * 0.03 * 0.03;
yearThreeSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03;
yearFourSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03;
yearFiveSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
yearSixSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
yearSevenSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
......

you need to set the array again…

// first, empty the array
savingsperyear.length = 0; 
// then, fill it with what you need (note I got a bit lost with your code, but this should get you going.....! :)
savingsperyear.push(yearOneSaving);
savingsperyear.push(yearTwoSaving);
savingsperyear.push(yearThreeSaving);
// etc..... (there are other ways to do this, I'm just showing it step by step)

Leave a comment