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($('').html('Row ' + key + '
'));
// 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 = $('').appendTo(".list"),
$a = $("", {text: 'Row ' + key}).appendTo($li),
$ol = $('
').appendTo($li);
$.each(values, function(i, val) {
$("", {text: val}).appendTo($ol);
});
});
});
I recommend using the $("
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.
No comments:
Post a Comment