0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I'm wondering how to parse the original numbers to ints, instead of strings, as they become with the above code? You could put + in front of v[c] to parse all values, but then "CENTRAL" tries to become a number as well, which obviously doesn't work.
@Khaine775 Fixed.
That's a very elegant solution, thanks for your inspiration!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.