Question

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];
    }
}
Was it helpful?

Solution

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.

OTHER TIPS

I'm glad you figured it out, @cdietschrun.

Version 4 of D3 allows you to do this a little more simply. It introduces a columns property, which creates an array of column headers (i.e. the dataset's 'keys').

So, instead of using your code:

var mappedArray = d3.entries(data[0]),
    valueKey = mappedArray[1].key;

... you can use:

var valueKey = data.columns;

You can get keys (column names) using D3 v3 values() method like this:

const [dataValues] = d3.values(data)
const keys = Object.keys(dataValues)
console.log(keys);

I used d3.entries() as below:

for(i=0;i<data.length;i++)
{
    var temp = d3.entries(data[i]);
    for(j=0;j<temp.length;j++)
    if(temp[j].key == selectedx)
    myarray.push(temp[j].value);
}

Hope this helps :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top