d3 将 csv 文件导入数组 [英] d3 importing csv file to array

查看:42
本文介绍了d3 将 csv 文件导入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 d3.csv() 方法导入 .csv 文件.这是我的代码:

I am trying to import a .csv file using the d3.csv() method. Here is my code:

d3.csv("data.csv", function(data) {
  console.log(data);
})

我以为我会得到一个包含对象的数组,每个对象代表我的 .csv 文件的一行(其中有 50 个).不过,我实际上得到的是一系列独立的对象.也就是说,该函数已将 50 个对象记录到我的控制台,不是一个包含 50 个对象的数组.我误解了这种方法吗?如果是这样,我怎样才能得到这样的数组?

What I thought I would get is an array containing objects, each representing a line of my .csv file (of which there are 50). What I'm actually getting, though, is a series of independent objects. That is, the function has logged 50 objects to my console, not one array containing 50 objects. Am I misunderstanding this method? If so, how can I get such an array?

推荐答案

在 d3 v5 中,用于获取数据的 API 发生了很大变化,随着底层工作从使用 XMLHttpRequest 到 Fetch API.在之前版本的 D3 到 v4 中,您的代码会按照您预期的方式打印单个结果数组.d3.csv() 的新 API,但是,看起来像这样:

In d3 v5 the API for fetching data has changed quite a bit, which became necessary as the underlying workings have switched from using XMLHttpRequest to the Fetch API. In prior versions of D3 up to v4 your code would have behaved as you expected printing the single resulting array. The new API for d3.csv(), however, look like this:

# d3.csv(input[, init][, row]) <>

# d3.csv(input[, init][, row]) <>

进一步的文档提供了解释供您观察:

Further down the docs provide an explanation for your observation:

如果只指定了initrow之一,如果是函数则解释为row转换函数,否则解释为一个初始化对象.

If only one of init and row is specified, it is interpreted as the row conversion function if it is a function, and otherwise an init object.

在您的代码中,d3.csv() 的第二个参数是一个函数,因此被解释为行转换函数.因为行转换函数是针对输入文件中的每一行执行的,所以您会看到每个对象单独打印,而不是一次打印整个数组.

In your code the second argument to d3.csv() is a function and is, thus, interpreted as the row conversion function. Because the row conversion function is executed for every single row in your input file you see each object printed individually instead of the whole array at once.

由于 d3.csv() 返回一个 Promise,正确的用法应该是这样的:

Since d3.csv() returns a Promise the correct usage would be like this:

d3.csv("data.csv")
  .then(function(data) {
    console.log(data);
  });

这里的data指的是整个对象数组.

Here data refers to the entire array of objects.

这篇关于d3 将 csv 文件导入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆