This is from d3
csv API document:
d3.csv("path/to/file.csv")
.row(function(d) { return {key: d.key, value: +d.value}; })
.get(function(error, rows) { console.log(rows); });
How can I pass the rows
to a var data
while not just console.log
it. I just want the data from csv but I am not familiar with JavaScript.
This is from d3
csv API document:
d3.csv("path/to/file.csv")
.row(function(d) { return {key: d.key, value: +d.value}; })
.get(function(error, rows) { console.log(rows); });
How can I pass the rows
to a var data
while not just console.log
it. I just want the data from csv but I am not familiar with JavaScript.
1 Answer
Reset to default 20The answer here only applies to d3 v4 and below. Starting with d3 v5, this method has changed. See this answer for the latest solution.
Keep in mind that it's impossible to have d3.csv()
return any data, because the data has to first load. That's why we use callback functions, which get invoked once the data is loaded (you can learn more by researching about "asynchronous javascript").
You still can assign your loaded data to a variable, but you have to keep in mind the implication asynchronous functions.
// This will be assigned to rows, once the data is ready.
var myData = null;
d3.csv("path/to/file.csv")
.row(function(d) { return {key: d.key, value: +d.value}; })
.get(function(error, rows) {
console.log(rows);
myData = rows;// Now you can assign it
myDataIsReady()// Now you can draw it
});
// IMPORTANT NOTE! Here myData is still null
console.log(myData);// will trace null
function myDataIsReady() {
console.log(myData);// will trace the data that was loaded
// Here you can draw your visualization
}
The point is that you can't draw anything until your CSV is loaded and parsed. So no matter what, your drawing code has to live inside some function that gets called from the d3.csv
callback.
It's possible to structure your code such that you'd never need to assign rows
to a variable (you'd just pass rows
into the function that draws the data).
data
array? – cdmckay Commented Jun 14, 2013 at 18:19data
is over there. – holys Commented Jun 14, 2013 at 18:23