原代码
冗余案例 1
// 结算方式: 1现结,5月结,8双月结,3签收结
let findItem1 = res.data.find((a) => a.paymentTerms === '1')
findItem1 ? (this.xianJieForm = findItem1) : ''
let findItem5 = res.data.find((a) => a.paymentTerms === '5')
findItem5 ? (this.yueJieForm = findItem5) : ''
let findItem8 = res.data.find((a) => a.paymentTerms === '8')
findItem8 ? (this.shuangYueJieForm = findItem8) : ''
let findItem3 = res.data.find((a) => a.paymentTerms === '3')
findItem3 ? (this.qianShouForm = findItem3) : ''
冗余案例 2
if (this.paymentTermsArr.includes('1')) {
obj.rules.push(this.xianJieForm)
}
if (this.paymentTermsArr.includes('5')) {
obj.rules.push(this.yueJieForm)
}
if (this.paymentTermsArr.includes('8')) {
obj.rules.push(this.shuangYueJieForm)
}
if (this.paymentTermsArr.includes('3')) {
obj.rules.push(this.qianShouForm)
}
配置对象后
// 初始化表单对象
let formObjects = {
'1': 'xianJieForm',
'5': 'yueJieForm',
'8': 'shuangYueJieForm',
'3': 'qianShouForm'
};
// 结算方式: 1现结,5月结,8双月结,3签收结
res.data.forEach((item) => {
if (formObjects[item.paymentTerms]) {
this[formObjects[item.paymentTerms]] = item;
}
});
优化2
// 初始化表单对象
let formObjects = {
'1': this.xianJieForm,
'5': this.yueJieForm,
'8': this.shuangYueJieForm,
'3': this.qianShouForm
};
// 遍历paymentTermsArr数组,检查每个元素是否在对象中,并将相应的表单对象添加到obj.rules数组中
this.paymentTermsArr.forEach((term) => {
if (formObjects[term]) {
obj.rules.push(formObjects[term]);
}
});