Chartjs-Initialize several charts in a loop

0👍

A quick solution is to clone the needed part of the object, with the handy function(s) JSON.parse and JSON.stringify, it makes sure it breaks all references (as mentioned on mdn).

container.querySelectorAll('canvas').forEach(canv => {
    const chartOptions = JSON.parse(JSON.stringify(chartConfigs[canv.dataset.type]));
    chartOptions.data.datasets[0].data = JSON.parse(canv.dataset.data);
    if(canv.dataset.labels != undefined){
        chartOptions.data.labels = JSON.parse(canv.dataset.labels);


    console.log(JSON.stringify(chartOptions));
    new Chart(canv, chartOptions);
});

Since I can’t see any functions in the object chartOptions the serializing and deserializing should be no problem?

Update, for object with functions (for your specific case):

I see two easy options,

  1. just extract the functions from the base object and just pass the current object

  2. Or if you don’t want to alter the chartConfigs object, just use the prototype function, call (link to documentation). With other words change the function calls to:

    // clone
    const chartOptions = JSON.parse(JSON.stringify(chartConfigs[canv.dataset.type]));
    ...
    let id = 1;
    let value = 100;
    
    // call the function
    chartConfigs[chartOptions.typ].testFunction.call(chartOptions, id, value);
    ...
    

(if testFunction would be a function, with 2 parameters ( id, value))

Is not very sexy, but is a fast solution, that will need little code modifications.

Leave a comment