To illustrate this issue let's take the following simple data example where I have a list of objects to display. Each object is composed of a shape and a variable list of lines
var data = [
{
"shape": "circle",
"x": 10,
"y": 20,
"lines": [
{x1: "-10", y1: "-10", x2: "10", y2: "10"}
]
},
{
"shape": "rect",
"x": 30,
"y": 20,
"lines": [
{x1: "-10", y1: "-10", x2: "10", y2: "10"}
]
},
{
"shape": "circle",
"x": 50,
"y": 20,
"lines": [
{x1: "-10", y1: "-10", x2: "10", y2: "10"},
{x1: "-10", y1: "10", x2: "10", y2: "-10"}
]
},
{
"shape": "rect",
"x": 70,
"y": 20,
"lines": [
{x1: "-10", y1: "-10", x2: "10", y2: "10"},
{x1: "-10", y1: "10", x2: "10", y2: "-10"}
]
}
];
I know I can use the filter() function to differenciate the shapes so I can create the shapes like this:
var shapes = svg.selectAll(".shape")
.data(data)
.enter()
.append("g")
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
var circles = shapes.filter(function (d) {
return d.shape == "circle"
})
.append("circle")
.attr("r", 10);
var rect = shapes.filter(function (d) {
return d.shape == "rect"
})
.append("rect")
.attr("transform", "translate(-5, -5)")
.attr("width", 10)
.attr("height", 10);
My issue then is to also append the variable amount of lines depending on data.
I see how I could happend only the first line like this:
shapes.append("line")
.attr("stroke", "red")
.attr("x1", function (d) {
return d.lines[0].x1
})
.attr("y1", function (d) {
return d.lines[0].y1
})
.attr("x2", function (d) {
return d.lines[0].x2
})
.attr("y2", function (d) {
return d.lines[0].y2
})
But I don't see how to do if the number of lines are variable.
What would be the correct way to achive this?
I created a fiddle with this example here: http://jsfiddle.net/Lm8XB/1/