在D3中读取CSV并将其转换为数组数组

时间:2017-03-23 13:17:10

标签: javascript arrays csv d3.js

我将以下小数据集硬编码到我的代码中的变量中:

var dataset = [['CENTRAL', 44, 552, 18565], 
                ['NORTHERN', 42, 945, 20092], 
                ['SOUTHERN', 96, 795, 30095], 
                ['PARK', 1, 640, 9341], 
                ['MISSION', 66, 1198, 18542], 
                ['TENDERLOIN', 23, 113, 10735], 
                ['RICHMOND', 9, 561, 9082], 
                ['TARAVAL', 81, 789, 11966], 
                ['INGLESIDE', 5, 1368, 13414], 
                ['BAYVIEW', 7, 985, 14711]];

现在,此数据集直接来自.csv文件,如下所示:

District,Prostitution,VehicleTheft,Totalcrimecount
CENTRAL,44,552,18565
NORTHERN,42,945,20092
SOUTHERN,96,795,30095
PARK,1,640,9341
MISSION,66,1198,18542
TENDERLOIN,23,113,10735
RICHMOND,9,561,9082
TARAVAL,81,789,11966
INGLESIDE,5,1368,13414
BAYVIEW,7,985,14711

但是,我显然希望能够阅读该文件,我曾试图使用此文件:

var dataset_csv = d3.csv("datafile.csv", function(d){
    console.log(dataset_csv = d)
}); 

这给了我一个看起来像这样的对象数组:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

District: "CENTRAL"
Prostitution: "44"
Totalcrimecount: "18565"
VehicleTheft: "552"

我的问题是,它可能是微不足道的,我如何将这些对象转换为像我的初始数据集一样的数组数据结构?我已经和它斗争了一段时间了。任何提示都非常赞赏。

1 个答案:

答案 0 :(得分:2)

使用Array#map迭代每个对象,Object.keys仅捕获键值。



var dataset_csv = [{District: "CENTRAL", Prostitution: "44", Totalcrimecount: "18565", VehicleTheft: "552"}, {District: "WEST", Prostitution: "22", Totalcrimecount: "4324", VehicleTheft: "53"}, {District: "EAST", Prostitution: "11", Totalcrimecount: "23434" , VehicleTheft: "76"}],
    datasetArr = dataset_csv.map(v => Object.keys(v).map(c => Number(v[c]) ? Number(v[c]) : v[c]));
    
    console.log(datasetArr);