user1823812 user1823812 - 5 months ago 70x
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) { = parseDate(;
d.close = +d.close;

// Scale the range of the data
x.domain(d3.extent(data, function(d) { return; }));
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 + ")")

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

In this particular example I got from, 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,

What am I doing wrong here?


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]).