AmericanCities
AmericanCities

Reputation: 139

Nested JSON structure to build side-by-side d3.js charts

I'm currently stuck on how to traverse a JSON structure (I created) in order to create side-by-side donut charts. I think I've created a bad structure, but would appreciate any advice.

I'm working from Mike Bostock's example here: http://bl.ocks.org/mbostock/1305337 which uses a .csv file for source data.

In that example he uses d3.nest() to create a nested data structure with an array of flight origins.

  var airports = d3.nest()
      .key(function(d) { return d.origin; })
      .entries(flights);

He is then able to bind that new data structure to a new div selector:

 var svg = d3.select("body").selectAll("div")
  .data(airports)
.enter().append("div")

Which allows him to create a donut chart for each flight origin.

My JSON data looks like the following:

{"years": [
  {
    "year": 2015,
    "type": "bestSellers",
    "chartOne":  [
        {
          "label": "smarties",
          "value": 11
        },
        {
          "label": "nerds",
          "value": 13
        },
        {
          "label": "dots",
          "value": 16
        },
        {
          "label": "sour patch kids",
          "value": 61
        }
    ],
    "chartTwo": [
        {
          "label": "Pepsi",
          "value": 36
        },
        {
          "label": "sunkist",
          "value": 13
        },
        {
          "label": "coke",
          "value": 34
        }
    ]}

I'm a CS student, with little experience of data structure best practices and d3.js. The structure I created doesn't look "flat" to me so I'm not sure if I need to use d3.nest(). However, I'm not clear how to traverse chartOne and chartTwo using the structure as is.

I can get to the arrays within the charts: var chartOne = years[0].chartOne; var cartTwo = years[0].chartTwo;

But I would like to be able to have one object to access chart1 and chart2. I'm tempted to create another array block in my JSON, but not clear if there isn't a more simple approach.

Upvotes: 0

Views: 522

Answers (1)

Mark
Mark

Reputation: 108537

No, you don't need to use .nest here. The easiest way to build the required data structure is as you suggest (d3 always wants an array to iterate over):

var nestedData = [ years[0].chartOne, years[0].chartTwo ];

After that, it's as simple as cleaning up the accessor functions for your data and Bostock's example works well.

Example here.

enter image description here

Upvotes: 1

Related Questions