Making Nested JSON Javascript

依然范特西╮ 提交于 2021-01-28 19:58:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!