Looking at my JSON data, here is an example of what it contains.
var data = [
{ animal: 'dog', names: [ 'mark', 'cooper', 'pooch' ] },
{ animal: 'cat', names: [ 'mary', 'kitty' ]
];
Now, I want to use d3
to create SVG elements based on this data in a specific format.
<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 start creating the g
element, I usually follow this process. The g
variable helps me in appending more elements later.
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(' + ... + ')'; }
});
Once the g
is set up, I can add the first text
element using the following steps.
g.append('text')
.attr({ x: '10', y: '10', fill: 'black' })
.text(function(d) { return d.animal; });
However, to append more elements to each g
by iterating over the array data[i].names
, how should I approach it?