JavaScript如何根据指定ID数组计算对象数组对应fees属性总和
实现ID匹配的fees属性求和功能
实现思路
- 遍历指定的查询ID数组,逐个匹配服务数组中对应Id的元素
- 对匹配成功的元素,将字符串格式的fees转为数字后累加
- 最终返回累加的总费用
完整实现代码
// 原始数据 const queryArray = ["1" , "2"] const services = [ { Id: "1", services: "Early Check-In", fees: "7500" }, { Id: "2", services: "Late Checkout", fees: "7500" }, { Id: "3", services: "Airport Chauffeur", fees: "25000" } ] // 求和函数 function calculateTotalFees(queryIds, serviceList) { let totalFees = 0 // 遍历所有要查询的ID for (const id of queryIds) { // 匹配对应Id的服务项 const targetService = serviceList.find(service => service.Id === id) // 匹配到则累加费用 if (targetService) { totalFees += Number(targetService.fees) } } return totalFees } // 测试验证 console.log(calculateTotalFees(["1","2"], services)) // 15000 console.log(calculateTotalFees(["1","3"], services)) // 32500 console.log(calculateTotalFees(["1","2","3"], services)) // 40000
简化写法(基于reduce)
function calculateTotalFees(queryIds, serviceList) { return queryIds.reduce((sum, currentId) => { const matched = serviceList.find(item => item.Id === currentId) return matched ? sum + Number(matched.fees) : sum }, 0) }
注意要点
- 原始数据中fees是字符串类型,必须通过
Number()转为数字后再累加,否则会出现字符串拼接的错误 - 加入匹配判断逻辑,就算查询ID数组中包含不存在的ID,也不会报错,只会跳过该ID的计算
内容的提问来源于stack exchange,提问作者Temitayo
相关产品推荐
相关产品推荐

