3

I have a large csv file that contains a country and a corresponding piece of data for that country.
In the form (excel example):

[Country1, Data1],
[Country2, Data2] etc

How would use a loop with the csv file to produce each item in the Geocharts array. Instead of writing them all out as in the example below.

 function drawRegionsMap() {

    var data = google.visualization.arrayToDataTable([
      ['Country', 'Popularity'],
      ['Germany', 200],
      ['United States', 300],
      ['Brazil', 400],
      ['Canada', 500],
      ['France', 600],
      ['RU', 700]
    ]);

I'm not really sure how to work with the csv file as I haven't worked with them in js before, however I did stumble upon the jquery-csv tool at https://github.com/evanplaice/jquery-csv but am not really understanding it fully.

Evan Plaice
  • 13,944
  • 6
  • 76
  • 94
user3663720
  • 305
  • 2
  • 12

1 Answers1

2

Your CSV file is already mostly correct for what you need. When you load the CSV in javascript, use the castToScalar parse function to make sure your numbers are parsed appropriately, then add the data to your DataTable. If your CSV contains a header row with column labels, you can just add it like your example:

var rawData = $.csv.toArrays(csv, {
    onParseValue: $.csv.hooks.castToScalar
});
var data = google.visualization.arrayToDataTable(rawData);

If your CSV does not contain headers, then you need to do some setup first:

var rawData = $.csv.toArrays(csv, {
    onParseValue: $.csv.hooks.castToScalar
});
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Value');
data.addRows(rawData);
asgallant
  • 26,060
  • 6
  • 72
  • 87
  • I'm the author of jquery-csv and I just wanted to give kudos. It's really inspiring to see users leverage some of the more advanced features of the library. Especially, people like you who go out of your way to help others. – Evan Plaice Jan 16 '18 at 01:05