D3节点和来自JSON的链接与嵌套的孩子数组 [英] D3 nodes and links from JSON with nested arrays of children
问题描述
我有一个JSON文件,如下所示:
I've got a JSON file that looks like this:
{
Object: {
children: Array[4]
...
Object: {
children: Array[1]
Object: {
children: Array[3]
...
},
Object: {
children: Array[1]
...
},
...
}
...
}
我的问题是当我试图把它变成一组节点和链接使用在d3强制布局,我不能得到它正确显示。我尝试使用array.map或forEach递归遍历所有的对象和自己创建链接,但这似乎过于乏味。
My problem is when I try to turn this into a set of nodes and links for use in a d3 force layout, I can't get it to display properly. I've tried using array.map or forEach to recursively go through all the objects and create the links myself, but this seems overly tedious.
有一个更简单的方法得到这个数据准备显示在强制布局?我缺少什么?
Is there a simpler way to get this data prepared to be displayed in a force layout? What am I missing?
推荐答案
我发现了一个有我需要的代码的示例。此功能使数据平坦。这是在Coffeescript,因为这是我使用。
I found an example that had the code I needed. This function flattens the data. It's in Coffeescript because that's what I use.
flatten: (root) =>
nodes = []
i = 0
recurse = (node) =>
if node.children
node.size = node.children.reduce(
(p, v) -> p + recurse(v)
, 0)
if !node.id
node.id = ++i
nodes.push(node)
node.size
root.size = recurse(root)
nodes
之后,我可以运行tree.layout
After I did that, I could just run tree.layout().links() to generate the links without having to do it manually.
@nodes = @flatten(@root)
@links = d3.layout.tree().links(@nodes)
希望帮助别人,因为这不是记录在docs或wiki中。
Hope that helps someone as this isn't documented in the docs or wiki.
这篇关于D3节点和来自JSON的链接与嵌套的孩子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!