[Chartjs]-Using unknown number of datasets in Chart.js

6👍

Problem:

You have an extra set of brackets surrounding the datasetdata variable.

Solution:

Remove the brackets and set the datasets to just datasetdata:

var graphData = {
    labels: labels,
    datasets: datasetdata
};

Explanation:

The datasets option accepts a parameter that is an array of dataset objects. The wanted structure looks as following:

datasets: [
    { dataset1 },
    { dataset2 }
]

In your code, you surrounded the datasetdata by a set of brackets:

var graphData = {
    labels: labels,
    datasets: [datasetdata]
};

By adding another set of brackets, you are basically setting datasets to an array which contains the datasetdata array. The code renders a result that looks as following:

datasets: [
    [ { dataset1 }, { dataset2 } ]
]

If you add select the value of the array at a specific index, you are extracting a single dataset from the datasetdata array.

var graphData = {
    labels: labels,
    datasets: [datasetdata[0]]
};

Your structure is then an array with a single dataset inside it:

datasets: [
   { dataset1 }
]

This code won’t throw and error, since the structure is valid, however, it will only display the first result.

Leave a comment