今天工作有一个数组对象需要处理,之前写了一个很复杂的遍历,完善后只需reduce即可。
假设需要处理的数组对象
phoneList = [
{phoneName:'苹果13-pro',price:8000},
{phoneName:'苹果13-pro',price:8000},
{phoneName:'三星-S20',price:7000},
{phoneName:'华为-P50',price:5000},
{phoneName:'三星-S20',price:7000}
]
使用reduce reduce方法
let newPhoneList = phoneList.reduce((total, cur) => {
const hasValue = total.findIndex(current => {
return current.phoneName === cur.phoneName
})
const quantity = 1
if (hasValue === -1) {
// 对设备名称和设备型号拆分
cur.deivceName = cur.phoneName.substring(0, cur.phoneName.indexOf('-'))
cur.deviceModel = cur.phoneName.substring(cur.phoneName.indexOf('-') + 1, cur.phoneName.length)
// 统计设备出现的数量
cur.quantity = 1
total.push(cur)
} else {
// 统计设备出现的数量
total[hasValue].quantity += quantity
total[hasValue].price = total[hasValue].price + cur.price
}
return total
}, [])
结果如下 完美
发文记录一下 方便日后查看