number40
number40

Reputation: 13

why does $.each makes array object undefined, but for loop works

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.

HTML - same for both

<ul id="treeList" class="list-group" style="margin: 0 auto; list-style-type: none;"></ul>

Code - working version

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 < len; i++) {
    var $item = $('<li><a href="#">' + nodes[i].name + '</a></li>');

    if (nodes[i].subcat.length) {
      var $subList = $('<ul></ul>');
      $item.append($subList);
      buildTree($subList, nodes[i].subcat);
    }

    $list.append($item);

  }
} 

Fiddle: https://jsfiddle.net/number40/0vpusefr/

Code - not working:

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 = $('<li><a href="#">' + node.name + '</a></li>');

    if (node.subcat.length) {
      var $subList = $('<ul></ul>');
      $item.append($subList);
      buildTree($subList, node.subcat);
    }

    $list.append($item);

  });
}

Fiddle for not working: https://jsfiddle.net/number40/qmLr14k8/

Upvotes: 1

Views: 49

Answers (1)

Brent Boden
Brent Boden

Reputation: 579

I found the error in you code, the each functions first parameter is the index.

function buildTree($list, nodes) {

  $.each(nodes, function(index, node) {

    var $item = $('<li><a href="#">' + node.name + '</a></li>');

    if (node.subcat.length) {
      var $subList = $('<ul></ul>');
      $item.append($subList);
      buildTree($subList, node.subcat);
    }

    $list.append($item);

  });

Replacing it by this should work.

Upvotes: 3

Related Questions