TypeScript处理Rest API数据分组求和出现字符串拼接问题如何解决
问题根因
你的代码只对参与累加的右侧item字段做了Number()转换,首次存入结果数组的item里Fields.16、Loan.LoanAmount两个字段仍为接口返回的字符串类型。JavaScript中字符串和数字执行+=操作时,会自动把数字转为字符串做拼接,不会触发数值求和,就是你遇到的问题的核心原因。
修复方案
有两种修复方式可选:
最小改动版本
仅修改累加逻辑,将已有分组项的字段值也转为数值后再相加:
getData() { this.branchService.getBranchPipeline() .subscribe(res => { console.log(res); this.branches = res; let datas = this.branches; this.dataProduct = datas.reduce((unit: any, item: any) => { let unitItem = unit.find((u: any) => u.fields['Fields.CUST01FV'] === item.fields['Fields.CUST01FV']); if(unitItem){ // 原有值也转为数字后再累加 unitItem.fields['Fields.16'] = Number(unitItem.fields['Fields.16']) + Number(item.fields['Fields.16']); unitItem.fields['Loan.LoanAmount'] = Number(unitItem.fields['Loan.LoanAmount']) + Number(item.fields['Loan.LoanAmount']); }else{ // 首次存入时提前转成数字,避免后续重复转换 const newItem = {...item}; newItem.fields['Fields.16'] = Number(newItem.fields['Fields.16']); newItem.fields['Loan.LoanAmount'] = Number(newItem.fields['Loan.LoanAmount']); unit.push(newItem); } return unit; },[]) console.log(this.dataProduct) }) }
性能优化版本
如果数据量较大,Array.find每次遍历数组的效率较低,可以改用Map存储分组映射,时间复杂度从O(n²)降到O(n):
getData() { this.branchService.getBranchPipeline() .subscribe(res => { console.log(res); this.branches = res; const groupMap = new Map(); this.branches.forEach(item => { const groupKey = item.fields['Fields.CUST01FV']; const field16 = Number(item.fields['Fields.16']); const loanAmount = Number(item.fields['Loan.LoanAmount']); if(groupMap.has(groupKey)){ const exist = groupMap.get(groupKey); exist.fields['Fields.16'] += field16; exist.fields['Loan.LoanAmount'] += loanAmount; }else{ const newItem = {...item}; newItem.fields['Fields.16'] = field16; newItem.fields['Loan.LoanAmount'] = loanAmount; groupMap.set(groupKey, newItem); } }) // 把Map的值转成数组就是最终结果 this.dataProduct = Array.from(groupMap.values()); console.log(this.dataProduct) }) }
内容的提问来源于stack exchange,提问作者fletch413
相关产品推荐
相关产品推荐

