title: Tree Structure from Adjacency List
body: <p>I am trying to generate a hierarchical tree object from a flat array with parent IDs.</p>
  
  <pre><code>// `parent` represents an ID and not the nesting level.
  var flat = [
      { id: 1, name: "Business", parent: 0 },
      { id: 2, name: "Management", parent: 1 },
      { id: 3, name: "Leadership", parent: 2 },
      { id: 4, name: "Finance", parent: 1 },
      { id: 5, name: "Fiction", parent: 0 },
      { id: 6, name: "Accounting", parent: 1 },
      { id: 7, name: "Project Management", parent: 2  }
  ];
  </code></pre>
  
  <p>The final tree object should look as follows:</p>
  
  <pre><code>{ 
      id: 1, 
      name: "Business", 
      children: [
          { 
              id: 2, 
              name: "Management", 
              children: [
                  { id: 3, name: "Leadership" },
                  { id: 7, name: "Project Management" }
              ]
          }
          // [...]
      ]
  }
  // [...]
  </code></pre>
  
  <p>You can see my current work on <a href="http://jsfiddle.net/xnpRa/">this fiddle</a>, but it only works on the first two levels.</p>
  
  <p>I thought about collecting the orphans (objects from <code>flat</code> without a parent in <code>tree</code> yet) and then looping over them again to see if they now have a parent. But that could mean many loops over the tree object, especially with many categories over multiple levels.</p>
  
  <p>I'm sure there is a more elegant solution.</p>