Home > Software design >  Switch with object.keys always return default value
Switch with object.keys always return default value

Time:11-05

i have a problem with a method, i am trying to get the value of a field errors in Angular forms, and then return a string if there is an error.

  public getFieldError(form: FormGroup, field:string):string | null{

    if(!form) return null

    const errors = form.controls[field].errors || {}
    
      for(const key in Object.keys(errors)) {
        console.log(Object.keys(errors))
        switch(key){
          case 'required':
            return 'required error';
          case 'minlength':
            return 'minlength error';
          default:
            return 'hi' 
        }
      
    }

    return null
  }

when i test the form, console.log(Object.keys(errors)) returns ['minlength'], so i think the second case, key == 'minlength' should activate, but it always returns the default value. Can you tell me what i am doing wrong? Thank you

CodePudding user response:

Object.keys returns an array. If you check that array's keys, they will be 0, 1, 2, etc. and not required and such.

Either use for of instead of for in so you iterate over the values of that array:

for (const key of Object.keys(errors)) {

...or use for in but without Object.keys so you directly iterate over the keys of your object1:

for (const key in errors) {

1: ...and any inherited properties, but in both cases only enumerable ones. Yes, there is a slight difference between the two options as explained here (Object.keys doesn't look at the prototype chain), but it should not be relevant for you, as your object most likely won't have any enumerable properties within ancestors in the prototype chain.

  • Related