简体   繁体   中英

D3 bind data of nested JSON document

I have data from a MongoDB in the following format. I'd like to create a multi line graph of this data similar to: http://bl.ocks.org/mbostock/3884955 with the date on the X axis, the duration on the Y axis and each job with as it's own separate line.

I'm having a hard time with the nested nature of my data - I've done some simple D3 charts before, but I'm not sure how to bind and access this data. I've seen several other similar examples on Stackoverflow (using the nest function etc.) but I'm not fully understanding it and am not sure if that would be the best solution. Any pointers on the best method to approach this would be very appreciated.

  {
      "result" : [
              {
                      "_id" : {
                              "month" : 1,
                              "day" : 20,
                              "year" : 2014,
                              "job" : "ABC"
                      },
                      "build_duration" : 432565
              },
              {
                      "_id" : {
                              "month" : 1,
                              "day" : 17,
                              "year" : 2014,
                              "job" : "ABC"
                      },
                      "build_duration" : 543256
              },
              {
                      "_id" : {
                              "month" : 1,
                              "day" : 17,
                              "year" : 2014,
                              "job" : "DEF"
                      },
                      "build_duration" : 87634
              },
              {
                  "_id" : {
                          "month" : 1,
                          "day" : 20,
                          "year" : 2014,
                          "job" : "DEF"
                  },
                  "build_duration" : 456230
              }
              ],
      "ok" : 1
  }

Here's the approach I would take. Nest the data based on the job ID and then draw the nested data. The code to do the nesting is simple, all you need is

var nested = d3.nest().key(function(d) { return d._id.job; })
               .entries(data.result);

Then you can draw it like this (assuming suitable definitions of the variables omitted here).

svg.selectAll("path").data(nested)
  .enter().append("path")
  .style("stroke", function(d) { return color(d.key); })
  .attr("d", function(d) { return line(d.values); });

Complete example here .

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