how do I iterate over object literal array with jquery $.each() method?
In the chrome debugger, it es back as "undefined, undefined".
Any help would be really appreciated. thanks!
var links = [
{ className : 'hover', url : '' },
{ className : 'hover-2', url : '' },
];
loopy(links)
function loopy(obj){
$.each(
obj,
function(){
console.log(obj.className + ', ' + obj.url);
}
);
}
how do I iterate over object literal array with jquery $.each() method?
In the chrome debugger, it es back as "undefined, undefined".
Any help would be really appreciated. thanks!
var links = [
{ className : 'hover', url : 'http://www.yahoo.' },
{ className : 'hover-2', url : 'http://www.foxnews.' },
];
loopy(links)
function loopy(obj){
$.each(
obj,
function(){
console.log(obj.className + ', ' + obj.url);
}
);
}
Share
Improve this question
asked Aug 7, 2011 at 2:18
cpeele00cpeele00
8934 gold badges15 silver badges30 bronze badges
3 Answers
Reset to default 6Try:
$.each(
obj,
function(i, val){
console.log(val.className + ', ' + val.url);
}
);
The $.each
function parameter takes two arguments -- the index of the current item in the array, and the second is the actual current value of the array.
See the API for some more explanation and examples.
You can see this fiddle to see it in action.
I just wanted to offer a slightly modified version of David's response that will be a little more gentle on the DOM when processing larger objects.
Original answer (above):
$.each(
obj,
function(i, val){
console.log(val.className + ', ' + val.url);
}
);
This solution works, but it generates an entirely new instance of the iterator function for every property in the object. There's no need for that, and I think you'll find more stable performance in larger applications by declaring specific methods to handle that sort of thing.
Try this:
// Process a property in your link object
function links_iterationHandler(i, val) {
console.log(val.className + ', ' + val.url);
}
// Traverse the link object and pass each result off to the method above
$.each(obj, links_iterationHandler);
This essentially does the same thing, but doesn't hammer on the DOM as much. It's not a big deal if you only have a few items in your object. But if you're dealing with a lot of data, like a big recordset loaded via Ajax, it will make a difference for sure.
Cheers!
I would try this: $.each([52, 97], function(index, value) { alert(index + ': ' + value); });
The first property is the index.
http://api.jquery./jQuery.each/