3
我的工作与嵌套JSON饲料与D3.js处理不同的子对象名称递归
当子对象被命名为children
我的代码工作正常,但我想成为少数的能显示节点其他物体,不只是名为children
。
例如,如果在children
对象内,我有另一个名为options
的对象。我也想显示那个对象的节点。
{
"item": [{
"children": [{
"name": "banana",
"definition": "this is a fruit",
"group": "n",
"options": [
{
"color": "red",
"shape": "square"
}
],
"countries": [
{
"color": "america",
"shape": "africa"
}
]
},
{
"name": "apple",
"definition": "this is a fruit",
"group": "n",
"options": [
{
"color": "red",
"shape": "square"
}
]
}]
}]
}
这里是一个递归函数,我有我的扁平化函数中:
// Returns a list of all nodes under the root.
function flatten(root) {
var nodes = [], i = 0;
function recurse(node) {
if (node.children) {
node.size = node.children.reduce(function(p, v) {
return p + recurse(v);
}, 0);
}
if (!node.id) node.id = ++i;
nodes.push(node);
return node.size;
}
root.size = recurse(root);
return nodes;
}
没有人有任何想法怎么一会去这样好吗?
您的预期结果是什么?这取决于你想要如何。但是如果使用'for'循环遍历对象,这将很简单。例如'for(child in parent){console.log(parent [child])}'会打印出每个'parent'对象的'child'节点。然后你可以用它递归递归。 – 2014-12-05 17:49:58
我想输出一个子对象中的每个项目作为一个节点。所以如果你有一个“儿童”对象和一个“国家”对象,那么我想同时显示两个节点。 – 2014-12-07 22:44:10
你只是在寻找叶子或所有节点 – RadleyMith 2014-12-08 18:35:32