admin管理员组

文章数量:1434929

I have an array arr=[{key: 'first'},{key: 'second'} ...], I want to go through that array and check if an element with a specific key exist and do something.

  arr.forEach(element => {
     if(element.key === 'first') {
        // do something
     } else { 
        // do something else
     }

     if(element.key === 'second') {
        // do something
     } else { 
        // do something else
     }         
  });

The thing is that when it goes through array, it first sees 'first' and it goes through if() statement, but it also goes through else() statement of 'second' item because it did't find it, and so it does when foreach goes through other items in array. I don't know how to make it to go through array one time and set if() else() appropriately. So when it finds 'first' I want it just to do if() of that item and not else() of others. I hope you understand. Thanks in advance!

Edit: My logic behind this code is that when I call database and find that array if there is no 'firstExercise' in that array, then it should add it to that db (I am using firebase so in else() I am calling db to create that exercise), and if there is'firstExercise' in array do nothing. Sorry for not clarifying that.

Edit2: Here is my original code:

  res.forEach(element => {
     if (this.numbOfFinished === 1) {
       if (element.key === 'firstExercise') {
           console.log('has')            
      } else {
        awardName = 'firstExercise'
        this.homeService.addAward(this.userId, awardName).then(() => {
          this.awardName = 'firstExercise';
         this.awarded = true;
         });
       }
     }
   });


     if (this.numbOfFinished === 5) {
       if (element.key === 'fifthExercise') {
           console.log('has')            
      } else {
        awardName = 'fifthExercise'
        this.homeService.addAward(this.userId, awardName).then(() => {
          this.awardName = 'fifthExercise';
         this.awarded = true;
         });
       }
     }
   });

I have an array arr=[{key: 'first'},{key: 'second'} ...], I want to go through that array and check if an element with a specific key exist and do something.

  arr.forEach(element => {
     if(element.key === 'first') {
        // do something
     } else { 
        // do something else
     }

     if(element.key === 'second') {
        // do something
     } else { 
        // do something else
     }         
  });

The thing is that when it goes through array, it first sees 'first' and it goes through if() statement, but it also goes through else() statement of 'second' item because it did't find it, and so it does when foreach goes through other items in array. I don't know how to make it to go through array one time and set if() else() appropriately. So when it finds 'first' I want it just to do if() of that item and not else() of others. I hope you understand. Thanks in advance!

Edit: My logic behind this code is that when I call database and find that array if there is no 'firstExercise' in that array, then it should add it to that db (I am using firebase so in else() I am calling db to create that exercise), and if there is'firstExercise' in array do nothing. Sorry for not clarifying that.

Edit2: Here is my original code:

  res.forEach(element => {
     if (this.numbOfFinished === 1) {
       if (element.key === 'firstExercise') {
           console.log('has')            
      } else {
        awardName = 'firstExercise'
        this.homeService.addAward(this.userId, awardName).then(() => {
          this.awardName = 'firstExercise';
         this.awarded = true;
         });
       }
     }
   });


     if (this.numbOfFinished === 5) {
       if (element.key === 'fifthExercise') {
           console.log('has')            
      } else {
        awardName = 'fifthExercise'
        this.homeService.addAward(this.userId, awardName).then(() => {
          this.awardName = 'fifthExercise';
         this.awarded = true;
         });
       }
     }
   });
Share Improve this question edited May 25, 2018 at 13:00 brass monkey 6,80111 gold badges43 silver badges66 bronze badges asked May 25, 2018 at 11:53 petar11199petar11199 1531 gold badge2 silver badges9 bronze badges 10
  • 1 How about a switch? – Biffen Commented May 25, 2018 at 11:55
  • Or, use a return true to continue. – Nisarg Shah Commented May 25, 2018 at 11:56
  • so if it is supposed to onlu go into the else than why are you seem like you should be using an else if – epascarello Commented May 25, 2018 at 11:56
  • 2 Or else if statements. – Jay Buckman Commented May 25, 2018 at 11:56
  • 2 So what exactly is the else for? You want the else branch to only execute if, e.g., 'first' wasn't found in the list at all? – deceze Commented May 25, 2018 at 11:58
 |  Show 5 more ments

3 Answers 3

Reset to default 1

I personally like to create arrays which makes the relation between a key and functions. So I can iterate and call the proper one.

What I like in this solution instead of using a switch/case or if/else forest is that you can apply automatic treatments and that you can easily make it to evolve.

const mapKeyFunc = [{
  key: 'first',

  func: async(x) => {
    console.log('Do something for key first');

    // here you can perform an async request and modify `this`
  },
}, {
  key: 'second',

  func: async(x) => {
    console.log('Do something for key second');

    // here you can perform an async request and modify `this`
  },
}];

const doStuff = async(arr) => {
  for (let i = 0; i < arr.length; i += 1) {
    const mapElement = mapKeyFunc.find(x => x.key === arr[i].key);

    await mapElement.func.call(this, arr[i]);
  }
};

const arr = [{
  key: 'first',
  otherStuff: 0,
}, {
  key: 'second',
  otherStuff: 42,
}];

doStuff(arr).then(() => {}).catch(e => console.log(e));


If you don't need the treatment to be synchronous, here we have an asynchronous method

const mapKeyFunc = [{
  key: 'first',

  func: async(x) => {
    console.log('Do something for key first');

    // here you can perform an async request and modify `this`
  },
}, {
  key: 'second',

  func: async(x) => {
    console.log('Do something for key second');

    // here you can perform an async request and modify `this`
  },
}];

const doStuff = async(arr) => {
  await Promise.all(arr.map(x => mapKeyFunc.find(y => y.key === x.key).func.call(this, x)));
};

const arr = [{
  key: 'first',
  otherStuff: 0,
}, {
  key: 'second',
  otherStuff: 42,
}];

doStuff(arr).then(() => {}).catch(e => console.log(e));

If you only want one option out of them to be executed (and then exiting out of the function), you could use else if statements like so:

arr.forEach(element => {
  if(element.key === 'first') {
     // do something
  } else if(element.key === 'second') {
     // do something
  } else { 
     // do something else
  }         
});

This will do pretty much exactly what you expect. If element.key == 'first', it'll do block one. Else, if element.key == 'second', it'll do block two. Else, it'll do block three.

You need to merge the if statements like this:

  arr.forEach(element => {
     if(element.key === 'first') {
        // do something
     } else if(element.key === 'second') {
        // do something else
     }         
  });

element.key has a single value in each iteration and you therefore need a single level of conditioning.

本文标签: javascriptIf else in foreachStack Overflow