简体   繁体   中英

How to destructing the array of object based on property name need to map the value

I have a below specified format of the response from server, i need to map the values based on fieldnames to the formcontrol names.

let userForm= ths.formbuilder.group({
firstName:[],
lastName:[],userName:[],
});

from the service i need to destructure the below response,

Here i have getting the exact values based on property, but i need to do for each property

let firstName= this.form.find(
  items=>   items.fieldName === 'firstName').fieldValue

 let  getUserName = this.form.find(items=>items.userName ==='userName').value


  console.log(firstName,getUserName,'test');

}

service response need to map to form control model based on field name.

   form:any =[
      {
          fieldName: 'firstName',
          fieldValue: 'johns smith',
          isVisible: true,
          isValidationEnabled: true
      },
      {
          fieldName: 'userName',
          fieldValue: 'admins',
          isVisible: true,
          isValidationEnabled: true
      },
      {
          fieldName: 'documentType',
          fieldValue: 'Invoice',
          isVisible: true,
          isValidationEnabled: true
      }
  ];

can anyone provide better solution

just write a function to convert it to an object?

function formArrayToObject(formArray: {fieldName: string, fieldValue: string}[]) {
  return formArray.reduce((acc, val) => {
    return Object.assign(acc, {[val.fieldName]: val.fieldValue});
  }, {});
}

call that on your array and you'll have a key-value object you can access as needed. or you can call reset or setValue or patchValue as needed on your form:

this.userForm.reset(formArrayToObject(this.form))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM