繁体   English   中英

如何遍历d3中的值的内部数组并添加相应的子元素?

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

我有如下所示的JSON数据。

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

根据这些数据,我需要按以下方式使用d3生成SVG元素。

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

要创建g元素,我需要执行以下操作。 我保留g变量以附加更多元素。

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(' + ... + ')'; } 
 });

现在,我可以如下添加第一个text元素。

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

如何通过遍历每个data[i].names数组将更多元素附加到每个g

一种方法是使用.each函数对每个数据点进行操作。 请注意,我们使用d3.select(this)获得当前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]; });
  }
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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