Please help clean this loop

Posted by Alex Angelini on Stack Overflow See other posts from Stack Overflow or by Alex Angelini
Published on 2011-01-11T18:41:50Z Indexed on 2011/01/11 18:53 UTC
Read the original article Hit count: 272

Filed under:
|
|
|

I do not code much in Javascript, but I have the following snippet which IMHO looks horrendous and I have to do this nested iteration quite often in my code. Does anyone have a prettier/easier to read solution?

function addBrowse(data) {
var list = $('<ul></ul>')

for(i = 0; i < data.list.length; i++) {
    var file = list.append('<li class="toLeft">' + data.list[i].name + '</li>')
    for(j = 0; j < data.list[i].children.length; j++) {
        var db = file.append('<li>' + data.list[i].children[j].name + '</li>')
        for(k = 0; k < data.list[i].children[j].children.length; k++)
            db.append('<li class="toRight">' + data.list[i].children[j].children[k].name + '</li>')
    }
}

$('#browse').append(list).show()}

Here is a sample data element

{"file":"","db":"","tbl":"","page":"browse","list":[
  {
     "name":"/home/alex/GoSource/test1.txt",
     "children":[
        {
           "name":"go",
           "children":[
              {
                 "name":"validation1",
                 "children":[

                 ]
              }
           ]
        }
     ]
  },
  {
     "name":"/home/alex/GoSource/test2.txt",
     "children":[
        {
           "name":"go",
           "children":[
              {
                 "name":"validation2",
                 "children":[

                 ]
              }
           ]
        }
     ]
  },
  {
     "name":"/home/alex/GoSource/test3.txt",
     "children":[
        {
           "name":"go",
           "children":[
              {
                 "name":"validation3",
                 "children":[

                 ]
              }
           ]
        }
     ]
  }]}

Thanks a lot

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery