Chart.js – How to write this Javascript more dynamically

0👍

Assuming your data is as long as you want your dataset is, you can do something like this;

const ctx = document.getElementById('myChart');

const data = JSONinput;

const datasets = data.map(row => ({
    label: row.Name,
    data: row.DataPoints.map(k => k.Score)
}));

new Chart(
    ctx,
    {
        type: 'line',
        data: {
  // The map on this line was not necessary
            labels: data[0].DataPoints.map(p => p.LogDate),
            datasets
        }
    });

Data passed into the chart ends up looking like this:

{
   "type":"line",
   "data":{
      "labels":[
         "2023-02-19T13:07:13.643",
         "2023-03-01T23:13:04.45"
      ],
      "datasets":[
         {
            "label":"Red",
            "data":[
               478.5,
               594
            ]
         },
         {
            "label":"Blue",
            "data":[
               546.5,
               657
            ]
         },
         {
            "label":"Green",
            "data":[
               687,
               757
            ]
         },
         {
            "label":"Purple",
            "data":[
               518,
               668
            ]
         }
      ]
   }
}

Leave a comment