Transform string into array

Asked

Viewed 757 times

2

I’m searching data and assembling a string to pass to the google graphics api but I’m having trouble, I’m doing it this way:

var variavel = "['Data', 'Membros', 'Visitantes'],";
for(var b = 0; b < pontos.length; b++){
    var obj = pontos[b][0];
    variavel = variavel + "['" + obj.data + "', " + obj.membros + ", " + obj.visitantes + "],"
   }

   variavel = variavel.replace(/'/g, '"');

   var parsVal = JSON.parse(variavel);

In this part I’m creating this string.

The problem you’re having is because of , the last time he passes on the go. On the console was plotted the following error:

Uncaught Syntaxerror: Unexpected token ,

After that I’m plotting in the graph div:

   google.charts.load('current', {'packages':['corechart']});
   google.charts.setOnLoadCallback(drawChart);

   function drawChart() {
    var data = google.visualization.arrayToDataTable(parsVal);

    var options = {
     title: 'Membros x Visitantes',
     curveType: 'function',
     legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
   }

My chart is not appearing on the page.

In the documentation this telling me to do this way:

<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
  }
</script>

but what I need is to do it dynamically, to take the data when the page is loaded. This graph I’m taking here:

https://developers.google.com/chart/interactive/docs/gallery/linechart
  • 2

    I think the problem lies before all this, in the stretch var variavel = "['Data', 'Membros', 'Visitantes'],";. In this excerpt could already leave formatted as a Javascript array and even is almost there.. rsrs.. I assume that this data comes from some other language, right? (php, Asp, etc.).. And looking at the remaining comma at the end, you can see it’s pretty sloppy.. Therefore I believe that your question would not even exist if this passage were well done.

  • @Danielomine this data is placed by me because if you observe you will see that it is necessary to have it inside the array, and this is the first data to which it should be passed. And the data doesn’t come from another language, I’m taking it from localStorage and iterating it this way.

  • 3

    Of curiosity, what is the point of working with strings? It would be much easier to use native objects than to convert and disconnect, no? Setting up a string to parse later gives me a bad impression (but if you have a legitimate reason to do so, and can comment, maybe I understand the code better).

  • @Bacco actually this was a solution I found, I know I need to pass this to my chart, would have another way to do ? I’ll put what’s on the site as it should be.

  • in localstorage could already save this data in json format.. then it would facilitate things... would not have this problem in having to convert or anything.. So the problem is there, in the way you save the data in the localstorage

  • My localStorage works like a normal database, I have in it several tables that I identify with a suffix exemplo_, in this case I have several data, this data is calculated every time I enter my application, so I save in the table, what time I did, the amount of members and visitors, to subsequently pick up the chart, the problem is occurring when I am sending this array to google api, because I need to search

Show 1 more comment

1 answer

7


In your case, use string is an unnecessary step as you can use JS objects even to get the desired result.

Based on this, it follows a simplification of its original code:

var variavel = [['Data', 'Membros', 'Visitantes']];
for(var b = 0; b < pontos.length; b++){
    var obj = pontos[b][0];
    variavel.push( [ obj.data, obj.membros, obj.visitantes ] );
}

in this way, variavel will already contain the finished object without conversion.

To better understand, we started creating a array of array:

var variavel = [['Data', 'Membros', 'Visitantes']];

and here, we simply put each iteration a new array of 3 items in the main:

    variavel.push( [ obj.data, obj.membros, obj.visitantes ] );

Supposing data, membros and visitantes are respectively 1, 2 and 3 in the first iteration and 10, 20 and 30 in the second, thus the variable:

[
   ['Data', 'Membros', 'Visitantes'],
   [      1,        2,            3],
   [     10,       20,           30]
]

and so on.

See working on CODEPEN.

  • solved my problem.

  • Good that solved! Any doubt warn, it is nice you understand what was done, because it can improve your practice in JS.

  • I understand it was done, but this inattentive one was mixing two ideas. Now I’m having problems with updating an existing chart, see about this ?

  • I never used this API, but it seems to me the case to open a question separately with the functional code, and explain what you want to do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.