如何使用For循环在对象内循环对象

时间:2018-01-14 16:25:26

标签: javascript angular loops typescript

我目前正在开发一个角度5应用程序,并坚持做验证。我有一个包含姓名,电子邮件,性别和地址的表格。我使用FormGroupname将城市,州,国家/地区分组到地址中。我在组件中编写了一个for循环来遍历表单中的valueChanges并使用Validators抛出错误。以下是我的代码:

export class RegistrationComponent implements OnInit {
  registerForm: FormGroup;
  constructor(private fb: FormBuilder) { }
  ngOnInit() {
    this.createLoginForm();
  }

   validationMessages = {
    name: {
        required: 'Name is required.',
    },
    email: {
        required: 'Email is required.',
    },
    gender: {
        required:'Gender is required.'
    },
    city: {
        required: 'City is required.',
    },
    state: {
        required: 'State is required.',
    },
    country: {
        required: 'Country is required.',
    },
  registerFormErrors = {
     name: '',
     email: '',
     gender: '',
     address:{
         city:'',
         state:'',
         country:'',
     }
}

createLoginForm(): void {
this.registerForm = this.fb.group({
name: ['', [Validators.required]],
email: ['', [Validators.required]],
gender: ['',[Validators.required]],
sur_name: ['', [Validators.required]],
address: this.fb.group({
  city: ['',[Validators.required]],
  state: [''],
  country: ['',[Validators.required]],
})      

this.registerForm.valueChanges.subscribe(data => 
                        this.validateRegisterForm(data));

  validateRegisterForm(data: any): void {
     if (!this.registerForm) return;
       for (let field in this.registerFormErrors) {
         this.registerFormErrors[field] = '';
         let input = this.registerForm.get(field);
            if (input.invalid && input.dirty || input.invalid) {
              for (let errors in input.errors) {
                 this.registerFormErrors[field] = this.validationMessages[field][errors];
        }
      }
    }
  }

在上面的代码中,我能够遍历registerFormErrors,但问题在于地址。由于地址是一个对象,我无法循环地址组字段。如何修改for循环,以便我可以遍历所有值以及地址对象。

任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以执行一个循环来检查该值是否为Object。如果它是一个对象,你必须循环键。



let example = {
     name: 'Foo',
     email: 'Bar',
     gender: 'Male',
     address:{
         city:'A',
         state:'B',
         country:'C',
     }
}

Object.keys(example).forEach(key => {
    if (typeof example[key] === "object") {
        Object.keys(example[key]).forEach(subkey => {
            doValidation(example[key][subkey])
        })
    } else {
        doValidation(example[key]);
    }
})

function doValidation(key) {
    console.log(key);
}