什么是在d3.json中使用d3.csv组合多个csv文件数据输入的最佳方法? [英] What is the best way to combine multiple csv files data input using d3.csv in d3.json ?

查看:173
本文介绍了什么是在d3.json中使用d3.csv组合多个csv文件数据输入的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是javascript和d3的新手。我试图找到最好的方式结合多个csv外部文件到d3然后做它的东西。目前我使用类似下面的脚本一个文件。

I am still new to javascript and d3 . I am trying to find the best way to combine multiple csv external files into d3 then do something with it. Currently I am using script like this below for one file.

d3.csv("file1.csv",funciton(error,data) {

// do something 

} 

有没有办法,我可以连接 file1.csv + file2.csv + .. file9.csv
到一个文件类似于这个..在d3?

Is there a way that I can concatenate file1.csv + file2.csv + .. file9.csv into one file something similar to this .. in d3 ?

d3.csv( concat("file1.csv","file2,csv",..file9.csv") ,function(error,data) {

// do something 

} 


推荐答案

这里是一个只使用d3的解决方案,您可以在操作中看到它

Here is a solution just using d3. You can see it in action in this Plunkr.

Javascript代码是:

The Javascript code is:

function multiCsv(files, callback) {
  var results = [];
  var error = "";
  var filesLength = (files || []).length;
  var callbackInvoked = false;
  for (var i = 0; i < filesLength; i++) {
    (function(url) {
      d3.csv(url, function(data) {
        if (data === null) {
          error += "Error retrieving \"" + url + "\"\n";
        } else {
          results.push(data);
        }
        // all files retrieved or an error occurred
        if (!callbackInvoked && (error || results.length === filesLength)) {
          if (error) {
            callback(error, null); // might want to send partial results here
          } else {
            callback(null, d3.merge(results));
          }
          callbackInvoked = true;
        }
      });
    })(files[i]);
  }
}

您可以这样使用:

multiCsv(["file1.csv", "file2.csv", "file3.csv"], function (err, results) {
  if (err) {
    alert(err);
    return;
  }
  var ul = document.createElement('ul');
  for (var i = 0, len = results.length; i < len; i++) {
    var li = document.createElement('li');
    li.textContent = results[i].FirstName + ' ' + results[i].LastName + ', ' + results[i].Age;
    ul.appendChild(li);
  }
  document.body.appendChild(ul);
});

(这只是添加了一个< ul> 到合并数组的内容的页面)。

(This just adds a <ul> to the page with the contents of the merged array).

我没有全面测试这个函数,所以YMMV。但它适用于我在Chrome中的简单测试用例。

I haven't comprehensively tested this function, so YMMV. But it worked for my simple test case in Chrome.

这篇关于什么是在d3.json中使用d3.csv组合多个csv文件数据输入的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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