简体   繁体   中英

How do you call data from nested JSON array using d3?

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") 

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 eg

{
"meals":[
    {"name":"salad","month":"january"},
    {"name":"burger","month":"february"}, //etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM