JS数组对象的重复属性去重并计算重复次数,并将数组重复对象的某属性合并

引用:http://t.csdnimg.cn/hp0Bv
 

今天工作有一个数组对象需要处理,之前写了一个很复杂的遍历,完善后只需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
}, [])

结果如下 完美

发文记录一下 方便日后查看

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值