title: Creating a multi-level array from DOM elements' data attributes in jQuery
body: <p>Ok this <em>may</em> be a simple loop question that I'm just overthinking (would be far from the first time) but I'm going to post this just incase someone has a quick answer for me.</p>
  
  <p>I have an array of DOM elements like this:</p>
  
  <pre><code>&lt;ul id="array"&gt;
    &lt;li class='item' data-id="1"&gt;
      &lt;ul class="child"&gt;
        &lt;li class='item' data-id="2"&gt;&lt;/li&gt;
        &lt;li class='item' data-id="3"&gt;&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/li&gt;
    &lt;li class='item' data-id="4"&gt;&lt;/li&gt;
    &lt;li class='item' data-id="5"&gt;
      &lt;ul class="child"&gt;
        &lt;li class='item' data-id="6"&gt;&lt;/li&gt;
        &lt;li class='item' data-id="7"&gt;
          &lt;ul class="child"&gt;
            &lt;li class='item' data-id="8"&gt;&lt;/li&gt;
            &lt;li class='item' data-id="9"&gt;&lt;/li&gt;
            ...
          &lt;/ul&gt;
        &lt;/li&gt;
      &lt;/ul&gt;
    &lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p>I want to loop through that using jQuery and come out with something like:</p>
  
  <pre><code>var result = [
    {
      "id":1,
      "children":[
        {
          "id":2,
          "children":[]
        }, 
        {
          "id":3,
          "children":[]
        }
      ]
    },
    { 
      "id": 4,
      "children":[]
    },
    {
      "id": 5,
      "children":[
        {
          "id":6,
          "children":[]
        }, 
        {
          "id":7,
          "children":[
            {
              "id":8,
              "children":[]
            }, 
            {
              "id":9,
              "children":[]
            }
          ]
        }
      ]
    }
  ]
  </code></pre>
  
  <p>(Note that is obviously spaced out for easy reading :) )</p>
  
  <p>If that was the exact number of child ul items there would be, that would be an easy loop. The issue I'm having is that the list item tree could go as many levels down as a user wants (realistically, it will stop at some point but you get the idea) so it will need to continue to loop through the tree until there are no more.</p>