2

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]) + ")"
            });
          }

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! That fixed it. I knew something small was tripping me up. Thanks so much.
It also works for invalid names. For example, if you have a key named "1st", you can't write data.1st, but you can write data["1st"].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.