简体   繁体   中英

D3.js - accessing data in nested array

I have a data array that looks like this:

    var data = [
  {
    "key": "user",
    "values": [
      "roles",
      "manager",
      "otherRoles",
      "reports",
      "devices",
      "coffees"
    ]
  },
  {
    "key": "role",
    "values": [
      "assignments",
      "members",
      "otherMembers"
    ]
  },
  {
    "key": "assignment",
    "values": [
      "roles"
    ]
  },
  {
    "key": "Device",
    "values": [
      "owners",
      "roles"
    ]
  },
  {
    "key": "Coffee",
    "values": [
      "drinkers"
    ]
  }
];

I am attempting to render tables from SVG rectangles where the table header is the "key" and the table rows are the "values". The only way I was able to make this work was to give a unique incremental class to each table (table0, table1 etc.) I know this is terrible and prevents me from easily accessing all tables in the future. Here is the pertinent code:

                parentBox = svgContainer.selectAll('.table')
                    .data(data, function(d) {return d.key;})
                    .enter()
                    .append('g')
                    .attr('class', function(d, i) {
                        return "table" + i;
                    })
                    .attr("transform", function(d, i) {
                        return "translate(" + boxWidth*i + "," + rowHeight*i + ")"; 
                    });

I'd like to figure out the right way to access nested data in D3. Here is the code in its entirety: D3 Example

Turns out the solution just requires understanding selections better. I first created the parentBox container:

parentBox = svgContainer.selectAll('.table')
   .data(data, function(d) {return d.key;})
   .enter()
   .append('g')
   .attr('class', 'table') (etc.)

Then, when populating the table with rows I first selected the created tables, used the each method to loop through each table and create each row. The one trick was to use d3.select(this) to make sure the rows were created properly.

             svgContainer.selectAll('.table')
                .each(function (d, i) {
                    tableRows = d3.select(this).selectAll('.row')
                        .data(d.values)
                        .enter()
                        .append(g) (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