AdRock AdRock - 4 months ago 28
jQuery Question

Looping through javascript object and create nested list

I don't normally have a problem with looping through objects and arrays with jQuery but this has got me stumped.

I have an order list which I need to add list items to using the object. I'm trying to loop through the object and create a list item for each of the keys and inside of that list item, I need to create another ordered list with the values from the array.

I can get the outer list items working okay but when it comes to the nested lists, it all goes pear shaped.

var obj = {
2: ['a','b','c','d','e'],
3: ['a','b','c','d','e'],
4: ['a','b','c','d','e'],
5: ['a','b','c','d','e'],
};

$.each(obj, function(key, val) {
// create the parent list items
$('.list').append($('<li></li>').html('<a href="#">Row ' + key + '</a><ol></ol>'));

// create the nested list items
$.each(val, function(k, v) {
// this is where it goes wrong
});
});


I have searched SO for a solution and elsewhere but can't find anything that works for me

Answer

Not sure what "all goes pear shaped" means in your case, but this slight rewrite of your code works well:

$(function () {

    var obj = {
        2: ['a','b','c','d','e'],
        3: ['a','b','c','d','e'],
        4: ['a','b','c','d','e'],
        5: ['a','b','c','d','e'],
    };
    
    $.each(obj, function(key, values) {
        var $li = $('<li></li>').appendTo(".list"),
            $a  = $("<a>", {text: 'Row ' + key}).appendTo($li),
            $ol = $('<ol></ol>').appendTo($li);
    
        $.each(values, function(i, val) {
           $("<li>", {text: val}).appendTo($ol);
        });
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ol class="list"></ol>

I recommend using the $("<element>", {params: 'values'}) syntax to create elements with unknown data in jQuery to avoid any escaping issues right from the start.

Also note that iteration order for object keys is not defined in JavaScript. If you rely on a certain order, you must explicitly sort the object keys up-front and iterate the array of sorted keys instead of the object.

In those cases it's usually much easier (and more appropriate) to send arrays to the client instead of objects.