简体   繁体   中英

How do I loop through an inner array of values in d3 and add corresponding children elements?

I have JSON data that looks like the following.

var data = [ 
 { animal: 'dog', names: [ 'mark', 'cooper', 'pooch' ] },
 { animal: 'cat', names: [ 'mary', 'kitty' ]
];

From this data I need to generate SVG elements using d3 in the following way.

<svg id="mysvg" width="500" height="500">
 <g data-animal="dog" transform="translate(0,0)">
  <text x="10" y="10" fill="black">dog</text>
  <text x="10" y="25" fill="black">mark</text>
  <text x="10" y="40" fill="black">cooper</text>
  <text x="10" y="55" fill="black">pooch</text>
 </g>
 <g data-animal="cat" transform="translate(0, 100)">
  <text x="10" y="10" fill="black">cat</text>
  <text x="10" y="25" fill="black">mary</text>
  <text x="10" y="40" fill="black">kitty</text>
 </g>
</svg>

To create the g element I do something like the following. I keep the g variable around to append more elements.

var g = d3.select('#mysvg')
 .selectAll('g')
 .data(data)
 .enter().append('g')
 .attr({ 
  'data-animal': function(d) { return d.animal; }, 
  transform: function(d) { return 'translate(' + ... + ')'; } 
 });

Now I can append the first text element as follows.

g.append('text')
 .attr({ x: '10', y: '10', fill: 'black' })
 .text(function(d) { return d.animal; });

How do I append more elements to each g by iterating over each data[i].names array?

One way is to use the .each function to operate on each data point. Note that we used d3.select(this) to get the current g .

 g.each(function(d) {
    for(var i = 0; i < d.names.length; i++) {
     d3.select(this).append('text')
       .attr({ x: '10', y: '10', fill: 'black' })
       .text(function(d) { return d.names[i]; });
  }
 });

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