0

I'm trying to create a set of graphs using D3 and I'm having trouble figuring out how to access nested data structures in my JSON. The data looks something like this (truncated):

{ "date": "20120927", 
  "hours": [ 
           { "hour": 0, "hits": 823896 }, 
           { "hour": 1, "hits": 654335 }, 
           { "hour": 2, "hits": 548812 }, 
           { "hour": 3, "hits": 512863 }, 
           { "hour": 4, "hits": 500639 }
           ],
  "totalHits": "32,870,234", 
  "maxHits": "2,119,767", 
  "maxHour": 12, 
  "minHits": "553,821", 
  "minHour": 3 }

{ "date": "20120928", 
  "hours": [ 
           { "hour": 0, "hits": 1235923 }, 
           { "hour": 1, "hits": 654335 }, 
           { "hour": 2, "hits": 1103849 }, 
           { "hour": 3, "hits": 512863 }, 
           { "hour": 4, "hits": 488506 }
           ],
  "totalHits": "32,870,234", 
  "maxHits": "2,119,767", 
  "maxHour": 12, 
  "minHits": "553,821", 
  "minHour": 3 }

What I eventually want to do is create multiple radar graphs, one for each day, plotting the hits for each hour. But I'm having trouble even just getting inside the "hours" array. I can , for example, get a list of all the dates, like so:

   d3.select("body") 
  .append("ul") 
  .selectAll("li") 
  .data(data) 
  .enter() 
  .append("li")
  .text(function (d,i) {
    return d.date;
  });

But I can't get at anything more nested. Can someone help point me in the right direction?

1 Answer 1

1

Assuming data is an two-element array containing your two objects, you could do something like this:

d3.select("body").append("ul").selectAll("li")
    .data(data) // top level data-join
  .enter().append("li")
    .each(function() {
      var li = d3.select(this);

      li.append("p")
          .text(function(d) { return d.date; });

      li.append("ul").selectAll("li")
          .data(function(d) { return d.hours; }) // second level data-join
        .enter().append("li")
          .text(function(d) { return d.hour + ": " + d.hits; });
    });

This would give you a nested structure like this:

<ul>
  <li>
    <p>20120927</p>
    <ul>
      <li>0: 823896</li>
      <li>1: 654335</li>
      <li>2: 548812</li>
      <li>3: 512863</li>
      <li>4: 500639</li>
    </ul>
  </li>
  <li>
    <p>20120928</p>
    <ul>
      <li>0: 1235923</li>
      <li>1: 654335</li>
      <li>2: 1103849</li>
      <li>3: 512863</li>
      <li>4: 488506</li>
    </ul>
  </li>
</ul>

See also Mike's Nested Selections article.

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

1 Comment

Also this gist I did for myself to understand nesting: bl.ocks.org/d/4018151

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.