I need your help, I have a code and I need to optimize it, can anyone know how this could be? This is my code:
handlerChangeInfo(value, fieldName: string) {
if (fieldName === 'fullName') {
this.billingFields.full_name = value;
}
if (fieldName === 'address') {
this.billingFields.address = value;
}
if (fieldName === 'postalCode') {
this.billingFields.postal_code = value;
}
if (fieldName === 'city') {
this.billingFields.city = value;
}
if (fieldName === 'stateOrProvince') {
this.billingFields.state_or_province = value;
}
if (fieldName === 'taxId') {
this.billingFields.tax_id = value;
}
}
CodePudding user response:
You can create an object to map your field name values to the object key names
const obj = {
fullName: 'full_name',
address: 'address',
postalCode: 'postal_code',
city: 'city',
stateOrProvince: 'state_or_province',
taxId: 'tax_id'
}
handlerChangeInfo(value, fieldName: string) {
if (obj[fieldName]) {
this.billingFields[obj[fieldName]] = value;
}
}
CodePudding user response:
Map version
const obj = new Map([
['fullName', 'full_name'],
['address', 'address'],
['postalCode', 'postal_code'],
['city', 'city'],
['stateOrProvince', 'state_or_province'],
['taxId', 'tax_id']
]);
handlerChangeInfo(value, fieldName: string) {
if (obj.get(fieldName)) {
this.billingFields[obj.get(fieldName)] = value;
}
}