0👍
✅
This may be old but I had the same problem and even after 2 years (of this question existing) I couldn’t easily find a good answer. Eventually I did, so here it is, if not for anything else but for others to find it easier.
var this_data=[50,100]; //data to be loaded on the different datasets. this_data[0] to be loaded in dataset[0], this_data[1] to be loaded in dataset[1] and so on
var this_cntr; //a counter to iterate over this_data
this_cntr= 0;
myChart.data.datasets.forEach(iterate);
//myChart.data.labels.push('label_name'); //these are to update the graph
//myChart.update('none');
function iterate(item) {
item.data.push(this_data[this_cntr]);
this_cntr= this_cntr+ 1
}
There probably is a shorthand version of this by I don’t really care for shorthands.Maybe someone else can do it.
0👍
Check the length of your datasets
array. If the second data
key does not exist then create it.
let length = chart2.data.datasets.length;
if (length > 1) {
chart2.data.datasets[1] = data.traffic_tx;
} else {
chart2.data.datasets[] = {data: data.traffic_tx};
}
Or something more dynamic:
let length = chart2.data.datasets.length;
let i = 0;
Object.entries(data).forEach([key, value] => {
if (i < length) {
chart2.data.datasets[i] = value;
} else {
chart2.data.datasets[] = {data: value};
}
i++;
});
Source:stackexchange.com