Using if else inside for loop


#1
 for(var key in this.filteredusers){
      if(this.filteredusers[key].displayName == this.newuser.displayName){
        toaster.setMessage('Username '+this.newuser.displayName+ ' already exists');
        toaster.present();
        console.log('user exist'); //it works till here 
      }
      else{
        console.log('user does not exist'); //but it never displays this if above statement is wrong it 
      //simply doesn't display anything. some times it works. sometimes it does not work at all.
      }
}

#2

Hello,
please console.log key, this.filteredusers[key].displayName and this.newuser.displayName to see what it is.

Maybe also replace for …in with for(let i=0;i<filteredusers.length();i++) and see if it works (when filteredusers is an array)

for …in can be tricky, because it can gives index of array, propertynames…

Also change var to let, because var has function wide scope and let block wide scope.

Best regards, anna-liebt


#3
if (Object.keys(this.filteredusers).filter(key=>{return this.filteredusers[key].displayName == this.newuser.displayName}).length>0) 
               toaster.setMessage('Username '+this.newuser.displayName+ ' already exists');

Still ugly (data) structure I’d say.

Put all the users in an array…