1
我想通過複雜的JSON對象(如this one)進行深度優先搜索,並輸出新結構的新對象:Javascript:遞歸深度優先搜索基於d3的遞歸的分層重新排序()
[
{
name: "Blade Runner",
children : [
{Obj}, {Obj},{Obj}, ...
]
},
...
]
我已經看了d3.js的recurse()
功能作爲參考,但似乎無法總結我的頭周圍我怎麼會寫給出一個輸入JSON沒有預先存在的「孩子」陣列類似的功能:
function recurse(node, depth, nodes) {
//assumes children exist in node object
var childs = children.call(hierarchy, node, depth);
node.depth = depth;
nodes.push(node);
if (childs && (n = childs.length)) {
var i = -1, n, c = node.children = [], v = 0, j = depth + 1, d;
while (++i < n) {
d = recurse(childs[i], j, nodes);
d.parent = node;
c.push(d);
v += d.value;
}
if (sort) c.sort(sort);
if (value) node.value = v;
} else if (value) {
node.value = +value.call(hierarchy, node, depth) || 0;
}
return node;
}
你會怎麼寫一個新的功能像這樣在上面的JSON響應上做一個DFS?
應該在輸入對象上應用哪些規則來創建新的對象結構? – smnh 2013-03-24 00:27:14