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