In trying to make multiple svg elements using D3.js, I am using the following code which works given this data format:
// Data that works:
var data= [
{x:1, y:2, z:5},
{x:3, y:5, z:10},
{x:8, y:9, z:11}
]
// Make svg elements
var svg = d3.select('body').selectAll('svg')
.data(data)
.enter().append('svg')
.style('display', 'inline-block')
.style('width', width)
.style('height', height)
.append('svg:svg')
However, when my data is nested, no svg elements appear on the DOM:
var data = {
x: {
val1: 10,
val2: 20
},
y: {
val1: 15,
val2: 14
},
z: {
val1: 10,
val2: 20
}
}
I would like to create svg elements which correspond to each child object of data (x, y, and z). It seems like they automatically get created for each object in first representation of the data. How I can achieve this given the second data structure?
The
.data()function expects a normal array, so just an object/associative array won’t work. Have a look at thed3.entriesfunction, which will convert it to a normal array.