简体   繁体   English

d3获取树的所有节点

[英]d3 get all nodes of tree

I try to keep this as short as I can: 我尽力做到这一点:

In the snippet I have a Json which represents a tree. 在摘要中,我有一个代表一棵树的Json。 With the help of d3 I try to get all child nodes of the root as an Array. 在d3的帮助下,我尝试将根的所有子节点获取为数组。 For that I use the function "nodes". 为此,我使用功能“节点”。

The Problem is that my children key is called "_children" instead of "children". 问题是我的子项键称为“ _children”而不是“ children”。 I try to find a good solution to tell the nodes function to check " children" instead of "children". 我试图找到一个好的解决方案,告诉节点函数检查“ children”而不是“ children”。 If I remove the " " of all children keys it works. 如果我删除所有子键的“ ”,它将起作用。

 var json = {"_name":"root","_children":[{"_name":"Application","_children":[{"_name":"Application Heap","_children":[],"_color":"#0000ff", "MEMORY":20},{"_name":"Other","_children":[],"_color":"#000055","MEMORY":30},{"_name":"Statement Heap","_children":[],"_color":"","MEMORY":40}]}]}; console.log(json); // tell d3 that my children key is "_children" var treemap = d3.layout.treemap() .children(function(d) { return d._children; }) .value(function(d) { return d.MEMORY; }); // With this line I try to get all child nodes of the root element var nodes = treemap.nodes(json) .filter(function(d) {return !d._children; }); console.log(json); // d3 sets the value and everything else correct console.log(nodes); // for some reason I get an empty array 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

One possible solution (but not the one I want) is to rename the field recursive like that at first: 一种可能的解决方案(但不是我想要的解决方案)是首先像这样重命名字段递归:

var renameKeys=function(obj){
    if(obj._children){
        obj.children=obj._children;
        delete obj._children;
        obj.children.forEach(renameKeys);
    }
return obj;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM