title: Javascript: Recursive Depth First Search for hierarchical reordering based on d3's recurse()
body: <p>I'm trying to do a depth first search through a complex JSON object such as <a href="https://www.googleapis.com/freebase/v1/search?indent=true&amp;filter=%28all+name%3A%22Blade+Runner%22%29&amp;output=%28disambiguator%29" rel="nofollow">this one</a>, and output a new object with a new structure of: </p>
  
  <pre><code>[
      {
         name: "Blade Runner",
         children : [
             {Obj}, {Obj},{Obj}, ...
         ]
       },
       ...
  ]
  </code></pre>
  
  <p>I've looked at d3.js's <code>recurse()</code> function as reference, but can't seem to wrap my head around how I would write a similar function given an input JSON without pre-existing "children" arrays:</p>
  
  <pre><code>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 &amp;&amp; (n = childs.length)) {
      var i = -1, n, c = node.children = [], v = 0, j = depth + 1, d;
      while (++i &lt; 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;
  }
  </code></pre>
  
  <p>How would you write a new function like this to do a DFS on the JSON response above?</p>