Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:递归深度优先搜索,基于d3';s递归()_Javascript_Json_Recursion_Depth First Search - Fatal编程技术网

Javascript:递归深度优先搜索,基于d3';s递归()

Javascript:递归深度优先搜索,基于d3';s递归(),javascript,json,recursion,depth-first-search,Javascript,Json,Recursion,Depth First Search,我正在尝试通过一个复杂的JSON对象进行深度优先搜索,例如,并输出一个具有以下新结构的新对象: [ { name: "Blade Runner", children : [ {Obj}, {Obj},{Obj}, ... ] }, ... ] 我已经将d3.js的recurse()函数作为参考,但似乎无法理解如果输入JSON而没有预先存在的“子”数组,我将如何编写类似的函数: 函数递归(节点、深度、节点

我正在尝试通过一个复杂的JSON对象进行深度优先搜索,例如,并输出一个具有以下新结构的新对象:

[
    {
       name: "Blade Runner",
       children : [
           {Obj}, {Obj},{Obj}, ...
       ]
     },
     ...
]
我已经将d3.js的
recurse()
函数作为参考,但似乎无法理解如果输入JSON而没有预先存在的“子”数组,我将如何编写类似的函数:

函数递归(节点、深度、节点){
//假设节点对象中存在子节点
var childs=childs.call(层次结构、节点、深度);
node.depth=深度;
nodes.push(节点);
if(childs&(n=childs.length)){
变量i=-1,n,c=node.children=[],v=0,j=depth+1,d;
而(++i

您将如何编写这样的新函数来对上面的JSON响应执行DFS?

如前所述,您要创建的新结构的标准尚不清楚。不过,TJS()可能会帮助您遍历JSON结构,如您举例说明的结构

DefiantJS使用方法“search”扩展了全局对象,您可以使用该方法在JSON结构中搜索匹配项,而不考虑深度。该方法返回匹配元素的数组(如果未找到匹配项,则为空)

例如:
(这里的工作小提琴:)

这段代码下载JSON结构并搜索任何名为“Music Track”的元素,然后返回两个匹配项

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;
}
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 );
    });