user1823812 user1823812 - 7 months ago 128
Javascript Question

D3 dynamic json key names

When you want to make a graph in d3 and you read your input from a json file (for example) the code goes pretty much like this :

d3.json("data/data.json", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});

// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);

svg.append("path") // Add the valueline path.
.attr("d", valueline(data));

svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);

svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
});


In this particular example I got from d3noob.org, there is a json file with objects that have 2 keys (date and close). What if I don't know the key names of the json file and I have to use a string variable? For example :

d3.json("data/data.json", function(error, data) {
var var1 = "date";
var var2 = "close";
data.forEach(function(d) {
d.var1 = parseDate(d.var1);
d.var2 = +d.var2;
});


I tried doing that, but the console gives me an error


d3.min.js:1 Error: attribute d: Expected number,
"M0,NaNL106,NaNL212,…".


What am I doing wrong here?

Answer

Use the bracket [] notation to access an object property whose name is stored in a variable.

eg: d.var1 = parseDate(d.var1) becomes d[var1] = parseDate(d[var1]).