1

I have some data in a csv that I would like to read in using d3 (version 4) and assign to a global variable. All of the examples I can find online (here and here) read in a csv and then print the results to the console.

So if I run:

d3.csv("mydata.csv", function(data) {
  console.log(data[0]);
});

Or

d3.csv("mydata.csv", function(d) {
  return {
    country : d.country,
    month : d.month,
    count : +d.count
  };
}, function(data) {
  console.log(data[0]);
});

I get the first line of my csv file.

However, if I try to run a similar script and write the results to a variable, ie:

var mydata = d3.csv("mydata.csv");

Or

var mydata = d3.csv("mydata.csv", function(d) {
  return {
    country : d.country,
    month : d.month,
    count : +d.count
  };
}, function(data) {
  console.log(data[0]);
});

And try to examine the variable mydata in the console, I am given a list of methods, not the actual data. Ie,

enter image description here

What am I doing wrong? How to I assign the data in the csv to a global variable, so I can eventually use it for visualization? I think I am interested in a synchronous solution, so I am open to not using d3.csv() if there are other functions out there that will simply read in the data and assign it to a global variable.

Amadou Kone
  • 907
  • 11
  • 21
  • `d3.csv` returns an object related to the request, and that's what you're seeing in the image you shared. Answering your question: you are already assigning the data array to a variable in your first snippet, called `data`. – Gerardo Furtado Nov 18 '17 at 21:51
  • 1
    Sure, I am assigning my data to a variable called `data`, but only within the function that prints to console. Maybe more specifically, how to I assign my data to a global variable? – Amadou Kone Nov 18 '17 at 21:57
  • @AmadouKone assigning to a global doesn't work because reading csv is asynchronous. You need to access it in a callback or use a promise. – Mark Nov 18 '17 at 21:59
  • 1
    I am planning on making visualizations with the data in the csv. So should I make all of those visualizations within a callback function? The tutorial I am following just reads in the CSV to an object and uses that object. – Amadou Kone Nov 18 '17 at 22:09

0 Answers0