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

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

本文关键字:添加 数组 元素 内部 遍历 d3 何遍历      更新时间:2023-09-26

我有如下所示的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]; });
  }
 });