The other day I thought I saw an object iterator in jQuery that had a flag that could be set to recursively iterate over child objects. I thought it was part of jQuery.each(), but now I don't see that capability in the docs.
Is there any such iterator in jQuery that can be automatically recursive?
(I know how to do it in javascript. Just wondering if I actually saw what I thought I saw.)
Thanks much!
EDIT: To be clear, I was thinking of a utility method like jQuery.each() that will iterate recursively over javascript objects and their nested objects.
Given the example below, the each() method would iterate over all objects, including the nested one in myobj.obj2.key2.
I could have sworn that I saw something in jQuery docs about that, but now I can't find it.
Thanks.
var myobj = {
obj1: {key1:'val1', key2:'val2'},
obj2: {key1:'val1', key2: {nest1:'val1', nest2:'val2', nest3:'val3'}},
obj3: {key1:'val1', key2:'val2'}
}
$jQuery.each(myobj, function(key,val) {
// Code to run over each key/val pair
// Does so recursively to include all nested objects
})
The .find('selector') method is basically a recusive version of .children(), and will find any descendant object that matched the selector, as opposed to .children() which only finds objects in the first level of descendants.
2nd EDIT (I phrased badly the first time, and messed up the code a bit!):
Ok, I don't think this functionality as a flag would make sense: you can quite happily recurse through that object forever (believe me, I broke firefox doing it), so you need some sort of interaction to make sure you only recurse when the child object is a valid recursion candidate.
What you need to do is simply split the function like so:
var myobj = {
obj1: {
key1: 'val1',
key2: 'val2'
},
obj2: {
key1: 'val1',
key2: {
nest1: 'val1',
nest2: 'val2',
nest3: 'val3'
}
},
obj3: {
key1: 'val1',
key2: 'val2'
}
}
$jQuery.each(myobj, function(key, val) {
recursiveFunction(key, val)
});
function recursiveFunction(key, val) {
actualFunction(key, val);
var value = val['key2'];
if (value instanceof Object) {
$.each(value, function(key, val) {
recursiveFunction(key, val)
});
}
}
function actualFunction(key, val) {
/// do stuff
}
A slightly simlified version of @Ed Woodcock's version above. They way I needed to use this was to output an HTML bulleted list with named links.
var list = "<ul>";
$.each(data, recurse);
function recurse(key, val) {
list += "<li>";
if (val instanceof Object) {
list += key + "<ul>";
$.each(val, recurse);
list += "</ul>";
} else {
list += "<a href='" + val + "'>" + key + "</a>";
}
list += "</li>";
}
list += "</ul>";
$("#container").html(list);
you can do this much easier as such
$(this).children().each(function(index, element) {
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With