Daniel Wolfe Daniel Wolfe - 7 months ago 17
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:

.data(data.January)
it will work. However, when using the variable tracking the current month selected with
.data(data.monthName)
it returns a
TypeError
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. (
update()
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);
colored_bars.selectAll("rect")
.data(data.monthName)
.enter()
.append("rect")
.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

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