Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else in foreach

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;
         });
       }
     }
   });
like image 776
petar11199 Avatar asked Jan 19 '26 15:01

petar11199


2 Answers

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));
like image 113
Orelsanpls Avatar answered Jan 21 '26 05:01

Orelsanpls


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.

like image 31
Thomas Cohn Avatar answered Jan 21 '26 04:01

Thomas Cohn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!