jQuery recursive iteration over 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
}

Leave a Comment