Home > Blockchain >  setValue dynamic to object in angular7
setValue dynamic to object in angular7

Time:05-09

I have this code which I want to refactor to better solution:

    async onServerRequestForDraft(res: { value: {}; tabType: ETabType; }) {
        res.value = this.uiForm.value;
       
        res.value = this.data;
       res.value['brokerage'] = this.uiForm.value.brokerage != null ? this.uiForm.value.brokerage : { id: 0, name: null };
        res.value['org'] = this.uiForm.value.org; 
        res.value['selectedPhone'] = this.uiForm.value.selectedPhone || '';
        res.value['customerName'] = this.uiForm.value.customerName || '';
}

I can't use forEach because res is not an array. maybe another solution?

CodePudding user response:

u can use forEach on Object like this :

Object.entries(this.uiForm.value).forEach((item) => {
    // item[0]  object key
    // item[1]  object value
 });

CodePudding user response:

You don't need forEach for it to work though you can use it.

   async onServerRequestForDraft(res: { value: {}, tabType: ETabType }) {
      Object.assign(res.value, {
          'brokerage': this.uiForm.value.brokerage ?? { id: 0, name: null },
          'org': this.uiForm.value.selectedPhone ?? '',
          'customerName': this.uiForm.value.customerName ?? '';
      })

      return res;
}

If you want to use loop only, you can do it this way:

async onServerRequestForDraft(res: { value: {}, tabType: ETabType }) {

     for (const key in this.uiForm.value) {
         if (key === 'brokerage') {
          Object.assign(res.value, {key : this.uiForm.value[key] ?? { id: 0, name: null }});
          continue;
         }
         Object.assign(res.value, {key : this.uiForm.value[key] ?? ''});
      }
      

      return res;
}
  • Related