1

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/

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It is always useful to consult the documentation: api.jquery.com/jquery.each/#jQuery-each-array-callback
Thanks for the link @xram

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.