问题
I am trying to make nested JSON for the sunburst diagram however I am having some trouble. As you can see in this fiddle below that the children that share a parent name are not being applied to everything? I want the No Virtual to have the same Attributes as the Virtual Parent. However because they are the same name I am running into a problem?
Is there someway to check if the root of the tree are the same? And that way it can be different every time, however it is going to get more and more nested and these choices of the name are the same.
http://jsfiddle.net/cre96uf3/2/
// create a name: node map
var dataMap = data.reduce(function(map, node) {
map[node.name] = node;
return map;
}, {});
// create the tree array
var tree = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
tree.push(node);
}
});
// show what we've got
d3.select('body').append('pre')
.text(JSON.stringify(tree, null, ' '));
回答1:
There is d3.nest which makes your live much easier than this.
This is a very helpful tool to get used to nesting: http://bl.ocks.org/shancarter/raw/4748131/
Otherwise read up about it here: http://www.d3noob.org/2014/02/grouping-and-summing-data-using-d3nest.html
Good luck,
Kim
来源:https://stackoverflow.com/questions/29014888/making-nested-json-javascript