0

I'm using chart.js@2.9.4/dist/Chart.min.js.

I have an array (data) of objects that looks like this:

(4) […]
​
0: Object { Num: "5", "Label1": "6,342", "Label2": "3,051", … }
​
1: Object { Num: "6", "Label3": "6,247", "Label4": "3,042", … }

This array has 9 objects in it. I have another array (xLabels) with 9 entries in it for the Y axis.

Any help would really be appreciated!

Here's what my code looks like right now:

    for(i=1 ; i < Object.keys(data[0].length; i++) {
       datasets.push( {
            str = Object.entries(data[1])[i][1]
            label: Object.entries(data[1])[i][0],
            data: parseFloat(str.replace(/,/g, '.'))
        })
     }

new Chart(ctx, {
      type: 'line',

    datasets: [
      {
        labels: tLabels,
        data: datasets,
      }],
}
e-frank
  • 739
  • 11
  • 21

1 Answers1

0

replace your for loop with this:

data.forEach((dataObject) => {
    const data = Object.values(dataObject)
    const label = data.shift()
    data.map((entry) => (parseFloat(entry.toString().replace(/,/g, '.'))))
    datasets.push({
        label,
        data
    })
});

and your new Chart with this:

new Chart(ctx, {
  type: 'line',
  data: {
    labels: xLabels,
    datasets
  }
})

example of whats happening in console: example of whats happening in console:

LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • Thanks, but the labels are displaying but the line graph/data is not. My dataset looks like yours except that my data array has 9 entries vs 2. ```0: {…} ​​ _meta: Object { 0: {…} } ​​ data: Array(9) [ "6,342", "3,051", "10,144", … ] ​​ label: "55"``` . Does your graph render correctly? Thanks again – forgottenbanna Feb 01 '21 at 18:47
  • Can you please share all your code because it seems to work for me (https://jsfiddle.net/Leelenaleee/zdbea24j/3/) – LeeLenalee Feb 01 '21 at 21:46