Khaine775
Khaine775

Reputation: 2765

Reading CSV in D3 and converting it to array of arrays

I have the following small dataset hardcoded into a variable in my code:

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]];

Now, this dataset is taken directly from a .csv file, that looks like this:

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

However, I'd obviously like to be able to just read in the file, which I've attempted using this:

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

Which gives me an array of objects that look like this:

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

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

My question is, and it might be trivial, how can I transform those objects into an array data structure like my initial dataset? I've been battling with it for some time now. Any hints greatly appreciated.

Upvotes: 0

Views: 205

Answers (1)

kind user
kind user

Reputation: 41893

Use Array#map to iterate over each object and Object.keys to catch only the keys values.

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);

Upvotes: 2

Related Questions