2013-03-23 63 views
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?

+0

應該在輸入對象上應用哪些規則來創建新的對象結構? – smnh 2013-03-24 00:27:14

回答

0

正如所評論的,您要創建的新結構的標準尚不清楚。儘管如此,DefiantJS(http://defiantjs.com)可能會幫助您遍歷JSON結構,例如您所舉例說明的結構。

DefiantJS使用「搜索」方法擴展全局對象,您可以使用該方法搜索JSON結構中的匹配,而不管深度如何。該方法返回匹配元素的數組(如果未找到匹配項,則爲空)。

例如:
(在這裏工作小提琴:http://jsfiddle.net/hbi99/x6B3A/

var url = 'https://www.googleapis.com/freebase/v1/search?indent=true&filter=%28all+name%3A%22Blade+Runner%22%29&output=%28disambiguator%29'; 
Defiant.ajax(url) 
    .search('//*[name="Musical Track"]') 
    .each(function(item) { 
     console.log(item); 
    }); 

此代碼下載JSON結構和搜索名爲「音樂軌」的任何元素,並返回了兩場比賽。