我尽量保持尽可能短的时间:
在代码片段中,我有一个代表树的Json。在d3的帮助下,我尝试将根的所有子节点都作为数组。为此我使用函数"节点"。
问题是我的孩子的钥匙被称为" _children"而不是"孩子"。我试图找到一个很好的解决方案来告诉节点功能检查" children"而不是"孩子"。如果我删除" "所有儿童钥匙都有效。
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>
&#13;
答案 0 :(得分:0)
一种可能的解决方案(但不是我想要的解决方案)是首先将字段重命名为:
var renameKeys=function(obj){
if(obj._children){
obj.children=obj._children;
delete obj._children;
obj.children.forEach(renameKeys);
}
return obj;
};