JavaScript中forEach循环内多if条件不编写单独方法的最简写法
代码简化实现方案
核心思路是把重复处理逻辑的属性名统一存到数组遍历执行,单独处理inputValues的特殊映射逻辑,无需额外抽独立方法,简化后代码如下:
this.cfData.customAttributes.forEach(currentObj => { // 单独处理inputValues的特殊映射逻辑 if (currentObj.inputValues !== null) { currentObj.inputValues = Array.prototype.map.call(currentObj.inputValues, item => item.value).join(", "); } // 批量处理需要首字母大写转换的属性 const formatFields = ['objectType', 'dataType', 'isGridEligible', 'isInvoiceEligible'] formatFields.forEach(key => { if (currentObj[key] !== null) { currentObj[key] = currentObj[key].toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase()) } }) })
优化说明
- 消除了4段完全重复的判断和字符串转换逻辑,整体代码精简近50%
- 后续如果需要新增同格式转换规则的属性,只需要往
formatFields数组里追加属性名即可,可维护性更高 - 完全保留原有业务逻辑的判断规则,没有修改业务执行结果
内容的提问来源于stack exchange,提问作者vamsi
相关产品推荐
相关产品推荐

