Skip to content
Advertisement

How to ignore a value when (for loop) through object?

I’m looping through an object using for loop, and I would like to ignore some specific values when looping.

This block of code is responsible to loop through my object:

let acceptAll = function (rawContent){
   for(let i in rawContent)
   if(!rawContent[i]) return false;
   return true
};

I have a value in rawContent that I would like to ignore when looping through, is that possible?

Many thanks in advance!

Advertisement

Answer

You have a couple of options:

  1. if continue

  2. if on its own

Here’s if continue:

for (let i in rawContent) {
    if (/*...you want to ignore it...*/) {
        continue; // Skips the rest of the loop body
    }
    // ...do something with it
}

Or if on its own:

for (let i in rawContent) {
    if (/*...you DON'T want to ignore it...*/) {
        // ...do something with it
    }
}

Side note: That’s a for-in loop, not a for loop (even though it starts with for). JavaScript has three separate looping constructs that start with for:

  • Traditional for loop:

    for (let i = 0; i < 10; ++i) {
          // ...
    }
    
  • for-in loop:

    for (let propertyName in someObject) {
          // ...
    }
    

    (If you never change the value in propertyName in the loop body, you can use const instead of let.)

  • for-of loop:

    for (let element of someIterableLikeAnArray) {
          // ...
    }
    

    (If you never change the value in element in the loop body, you can use const instead of let.)

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement