最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - D3 csv return rows - Stack Overflow

programmeradmin0浏览0评论

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.

Share Improve this question asked Jun 14, 2013 at 18:15 holysholys 14.8k15 gold badges46 silver badges50 bronze badges 2
  • You mean you want to save the rows to a data array? – cdmckay Commented Jun 14, 2013 at 18:19
  • Please have a look at the picture f.cloud.github.com/assets/1198913/655940/…, the data is over there. – holys Commented Jun 14, 2013 at 18:23
Add a comment  | 

1 Answer 1

Reset to default 20

The 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).

发布评论

评论列表(0)

  1. 暂无评论