Google Chart - arrayToDataTable not an array error

Viewed 109

I have a backend in nodejs that generates an array and call a javascript function to plot a graph.

var data = google.visualization.arrayToDataTable(value)

The problem that I got a uncaught error:

enter image description here

Printing the variable value I have:

 [ [ 'ml', 'date' ],
  [ 'Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)',
    481 ],
  [ 'Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)',
    571 ] ]

Reading similar posts like Google Chart - uncaught error: not an array i tried:

var data = google.visualization.arrayToDataTable(JSON.parse(values));

But i get the following error:

enter image description here

If I hardcode values it works fine:

var values = google.visualization.arrayToDataTable([
    ['ml','date'],
    ['Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)',481 ],
    ['Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)',571 ]
]);

var data = google.visualization.arrayToDataTable(values);

I couldn't see any difference printing the variable from hardcoding.

Any ideia?

1 Answers

the array is most likely being passed as a string.
if so, you need to use --> JSON.parse

but you need to swap the single quotes (') for double quotes (")

see following snippet, which works...

var test = JSON.parse('[["ml","date"],["Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)",481 ],["Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)",571 ]]');
console.log(test);

while this snippet does not...

var test = JSON.parse("[['ml','date'],['Sun Nov 24 2019 13:30:00 GMT-0200 (Brasilia Summer Time)',481 ],['Sun Nov 24 2019 14:00:00 GMT-0200 (Brasilia Summer Time)',571 ]]");
console.log(test);

Related