Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

json - jQuery recursive iteration over objects

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
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...