To get the names of all non-leaf elements, you can do something like this.
var names = [];
function getNames(node) {
if(node.children) {
names.push(node.name);
node.children.forEach(function(c) { getNames(c); });
}
}
getNames(root);
After running this code, names
will contain all the names you want. To then generate a legend from that, you can use the names
array as the data:
var gs = svg.selectAll("g.name").data(names).enter().append("g").attr("class", "name");
gs.append("rect")
// set position, size etc
.attr("fill", d);
gs.append("text")
// set position etc
.text(String);
This will append a g
element for each name and within each g
element, append a rect
that is filled with the colour corresponding to the name and a text
element that shows the name.