Daniel Wolfe Daniel Wolfe - 2 years ago 68
Javascript Question

D3: Accessing Objects in Bound array using variables

I'm trying to animate monthly data across a map. I've stored each month's data all together within an array, and when I try to bind the data like so with:

it will work. However, when using the variable tracking the current month selected with
it returns a
in the console and does not render the rest of the application.

My guess is that I'm accessing the key values incorrectly, and that d3 has a unique way of handling that.

Below is the function that doesn't work. (
is fired when the slider controls change months.)

d3.json("data/avg_revisit.json", function(data) {
color.domain([20, 0]);
function update() {
var monthName = getMonthName(currentMonth);
.attr("width", getLandWidth())
.attr("class", "bars")
.attr("height", function(d) {
return projection([0, d.latitude - 0.5])[1] - projection([0, d.latitude])[1];
.attr("opacity", 0.6)
.style("fill", function(d) {
//Get data value
var value = d.average_revisit;

if (value) {
//If value exists…
return color(value);
} else {
//If value is undefined…
return "#ccc";
//Define position of each rectangle by it's latitude from the data
.attr("transform", function(d) {
return "translate(" + projection([-180, d.latitude]) + ")"

Answer Source

Use data[monthName] instead of data.monthName. If you are using a variable to access the key of an object you must use object[string variable].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download