我有这段代码,我想重构它以获得更好的解决方案:
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 || '';
}
我不能使用forEach,因为res不是数组。也许还有别的解决办法?
你不需要forEach来工作,尽管你可以使用它。
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;
}
如果你想只使用循环,你可以这样做:
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;
}
你可以像这样在Object上使用forEach:
Object.entries(this.uiForm.value).forEach((item) => {
// item[0] object key
// item[1] object value
});