Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I Loop through a complex JSON object but I want to stop the loop after n iterations

n = 0;
maxIterations = 100;
ObjectValues = function(v, k){
  if(n == maxIterations){
    if (typeof v == "object") {
      for (var kp in v) {
        if (Object.hasOwnProperty.call(v, kp)) {
          ObjectValues(v[kp], k != undefined ? k + "." + kp : kp);
        }
      }
    } else {
      console.log(k + ":" + v);
      n++;
    }
  }else{
    console.log('I should end the function');
    return false;
  }
};

But I can't exit the function with return false. The function gets called, even after I tried to exit it with return false.

share|improve this question
    
try if(n >= maxIterations) and let us know. –  Tolga Evcimen Jun 26 at 12:20
1  
n will never be bigger than maxIterations. So this doesn't work. An when i do it like this: n <= maxIterations, then it doesn't work too. But this is not the problem. The problem is, how to exit the function. –  Simon S. Jun 26 at 12:24
    
so, are you aware that you don't increase the n on your if case? –  Tolga Evcimen Jun 26 at 12:25
    
I do but just in the else. The function looks through all the objects in a object and if there are no more objects in a object it prints k and v. This information I want to get n times. That's why I increase the n just in the else case. –  Simon S. Jun 26 at 12:30
    
So tell us what exactly happens? You say "The function gets called, even after I tried to exit it with return false.", if you can get down to the return false; then it means you are already in the function, it is already called. I couldn't understand the question. –  Tolga Evcimen Jun 26 at 12:36

1 Answer 1

As I understand it, you want to recursively print maxiteration keys and their values:

n = 0;
maxIterations = 100;
ObjectValues = function(v, k){
  if(n < maxIterations){
    if (typeof v == "object") {
      for (var kp in v) {
        if (Object.hasOwnProperty.call(v, kp)) {
          if(! ObjectValues(v[kp], k != undefined ? k + "." + kp : kp) )
            return false;
        }
      }
    } else {
      console.log(k + ":" + v);
      n++;
    }
    return true;
  } else {
    console.log('I should end the function');
    return false;
  }
};
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.