Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have nested arrays in my json data, but I don't know how to call them in the d3 (beginner).

In the example below, I am trying to build an SVG bar chart, using data from the "January" array, nested in the "meals" array in Json.

The Json looks like this:

{
"meals":[
    {"january":[
        {},{}
    ]},

    {"february":[
        {},{}
    ]},

    {"march":[
        {},{}
    ]},
  }

And the d3 code looks like this. "chart" takes the user input of a drop down menu. In this case, it basically returns "meals":

    var chart = selection.options[selection.selectedIndex].id;

    var dataset = data[chart];

    var svg = d3.select ("body") 
                .append ("svg")
                .attr("width", w)
                .attr("height", svgHeight+30);


    svg.selectAll("rect") 
                .data(dataset.january) //***HERE is where I'm having trouble***
                    .enter()
                    .append("rect") 
share|improve this question
 
Is the json object already loaded? Or is it in a separate file? –  Adam Pearce Jul 9 at 19:56
 
Yes, it's in a separate file and already loaded. –  user2559519 Jul 9 at 20:03
 
.data(dataset) should work then; if not you probably should post a jsfiddle. Any number of things could be going wrong. –  Adam Pearce Jul 9 at 20:04
 
The value of data.meals is an array. Hence you would have to access it with dataset[0], dataset[1], .... However, since each of the objects only contains one property, you might wan to use an object instead of an array of objects. –  Felix Kling Jul 9 at 20:12
 
hhmmm...that doesn't seem to work. The page loads, but no rect is created. I need arrays, because I am trying to create a double bar chart and will be adding additional data. –  user2559519 Jul 9 at 21:52

1 Answer

d3.nest() can convert data like that into parseable arrays. These 'tutorial' examples are great: http://bl.ocks.org/phoebebright/raw/3176159/

Given that it's feasible with your project, it might otherwise be better to simply change your data formatting for an easier traversal e.g.

{
"meals":[
    {"name":"salad","month":"january"},
    {"name":"burger","month":"february"}, //etc...
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.