cdietschrun cdietschrun - 1 year ago 39
Javascript Question

d3 seems to assume I know the column names of a csv?

I have csv files that are generated, and I am trying to load them into d3 to graph them. The column names are based on the data, so I essentially can't know them in advance. With testing, I am able to load this data and graph it all well and nice if I know the names of the columns...but I don't in my use case.

How can I handle this in d3? I can't seem to find anything to help/reference this online or in the documentation. I can see when I log to the console data[0] from d3.csv that there are two columns and the values read for them, but I don't know how to refer arbitrarily to column 1 or 2 of the data without knowing the name of the column ahead of time. I'd like to avoid that in general, knowing my timestamps are in column 1 and my data is in column 2, if that makes sense.

Edit, my answer uses d3.entries to help learn the name of the unknown column, and then continues to access all objects with that index:

d3.csv("export.csv", function(error, data) {
var mappedArray = d3.entries(data[0]);
var valueKey = mappedArray[1].key;
data.forEach(function(d) {
d.value = d[valueKey];

Answer Source

You can use the d3.entries() function to transform an associative array into another array that contains an associative array with key and value keys for each key-value pair.