CacsAntibis
CacsAntibis

Reputation: 35

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!

Upvotes: 1

Views: 3380

Answers (3)

Pawan Sharma
Pawan Sharma

Reputation: 2342

You can maintain an array of values which you would like to ignore. For example

const valuesToIgnore = [1,5,15,20]
let acceptSome = (rawContent) => {
    for (let i of rawContent) {
        if (valuesToIgnore.includes(i)) {
        // These are the values you want to ignore
            console.log('Ignoring', i)
        } else {
        // These are the values you do not want to ignore
            console.log('Not Ignoring', i)
        }
    }
}

// And you invoke your function like this -

acceptSome([1,2,3,5,10,15,20,25])

Upvotes: 0

Imit
Imit

Reputation: 98

I guess you are searching for the continue keyword:

let array = [1,2,3,4]

for(let i of array){
    if(i === 2) continue
  console.log(i)
}

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074989

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.)

Upvotes: 2

Related Questions