title: why does $.each makes array object undefined, but for loop works
body: <p>I am attempting to iterate through a tree structure.  The tree is an array of JSON objects.  If I iterate in a for loop all is fine...but if I iterate using $.each the iterated object becomes undefined.  Any help understanding this would be great.</p>
  
  <p>HTML - same for both</p>
  
  <p><code>&lt;ul id="treeList" class="list-group" style="margin: 0 auto; list-style-type: none;"&gt;&lt;/ul&gt;</code></p>
  
  <p>Code - working version</p>
  
  <pre><code>var tree = [{
      "name": "Parent 1",
      "subcat": []
    },
    {
      "name": "Parent 2",
      "subcat": [{
        "name": "child 2",
        "subcat": [{
          "name": "grandchild 2",
          "subcat": []
        }]
      }]
    },
    {
      "name": "Parent 3",
      "subcat": []
    }
  ];
  
  buildTree($('#treeList'), tree);
  
  function buildTree($list, nodes) {
  
    for (var i = 0, len = nodes.length; i &lt; len; i++) {
      var $item = $('&lt;li&gt;&lt;a href="#"&gt;' + nodes[i].name + '&lt;/a&gt;&lt;/li&gt;');
  
      if (nodes[i].subcat.length) {
        var $subList = $('&lt;ul&gt;&lt;/ul&gt;');
        $item.append($subList);
        buildTree($subList, nodes[i].subcat);
      }
  
      $list.append($item);
  
    }
  } 
  </code></pre>
  
  <p>Fiddle: 
  <a href="https://jsfiddle.net/number40/0vpusefr/" rel="nofollow noreferrer">https://jsfiddle.net/number40/0vpusefr/</a></p>
  
  <p>Code - not working:</p>
  
  <pre><code>var tree = [{
      "name": "Parent 1",
      "subcat": []
    },
    {
      "name": "Parent 2",
      "subcat": [{
        "name": "child 2",
        "subcat": [{
          "name": "grandchild 2",
          "subcat": []
        }]
      }]
    },
    {
      "name": "Parent 3",
      "subcat": []
    }
  ];
  
  buildTree($('#treeList'), tree);
  
  function buildTree($list, nodes) {
  
    $.each(nodes, function(node) {
  
      var $item = $('&lt;li&gt;&lt;a href="#"&gt;' + node.name + '&lt;/a&gt;&lt;/li&gt;');
  
      if (node.subcat.length) {
        var $subList = $('&lt;ul&gt;&lt;/ul&gt;');
        $item.append($subList);
        buildTree($subList, node.subcat);
      }
  
      $list.append($item);
  
    });
  }
  </code></pre>
  
  <p>Fiddle for not working: <a href="https://jsfiddle.net/number40/qmLr14k8/" rel="nofollow noreferrer">https://jsfiddle.net/number40/qmLr14k8/</a></p>