1

I have a javascript string that contains all the data for "arrayToDataTable".

var pieData = "['Red', 3], ['Blue', 6] , ['Green', 8]";

My pie chart:

function drawPieChart() {
    var data = google.visualization.arrayToDataTable([
    ['Team', 'Votes'],
    pieData
    ]);

    var options = {         
        sliceVisibilityThreshold: 0,
        width: 620,
        height: 300,
    };

    var chart = new google.visualization.PieChart(document.getElementById('pieChart'));
    chart.draw(data, options);
  }

When the function is run, the following error is rendered "Invalid type for row 0".

Is there some simple way to make the string pieData usable for arrayToDataTable?

Hwende
  • 599
  • 2
  • 10
  • 25

1 Answers1

1

One of the solutions is to use eval() to evaluate the expression inside the string as JavaScript code. More information on this function is available here.

Solution

function drawPieChart() {
    var pieData = "['Red', 3], ['Blue', 6] , ['Green', 8]";
    var dataArray = [
      ['Team', 'Votes']        
    ];

    var newDataArray = dataArray.concat(eval("[" + pieData + "]"));
    var data = google.visualization.arrayToDataTable(newDataArray);

    var options = {         
       sliceVisibilityThreshold: 0,
       width: 620,
       height: 300,
    };

    var chart = new google.visualization.PieChart(document.getElementById('pieChart'));
    chart.draw(data, options);
  }

Once the String is evaluated as a JavaScript expression the array is concatenated into the dataArray to form your data array for your new chart .

RH7
  • 223
  • 1
  • 11