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