需求:在一些商品列表,优惠券列表,购物车…中时常会需要把相同商品归类起来展示,而不是一一罗列出来,这时就需要根据每个商品的唯一标识进行计算跟去重啦。
重点:计算方式
- 第一个数据时直接赋值num=1并追加到新数组里;
- 判断当前这条数据在新数组里是否存在,存在则num增加1,否则赋值num=1并追加到新数组中;
onLoad: function (options) {
var that = this;
var list = that.data.list;
var newList = [];//声明一个新数组
var num = 1; //数量
for (var i = 0; i < list.length; i++) {
if (i == 0) {
list[0].num = 1;
newList.push(list[0]);
} else if (newList.every(o => o.couponId != list[i].couponId)) {//不同商品
list[i].num = 1;
num = 1;
newList.push(list[i]);
} else if (newList.some(o => o.couponId == list[i].couponId)) {//相同商品
num = num + 1;
newList.find(o => o.couponId == list[i].couponId).num = num;
}
}
that.setData({
list: newList,
})
console.log("newList", newList);
},
list数据:
list: [{
id: 1,
name: "5折餐饮优惠券",
price: "50",
originalPrice: "100",
couponId: 1,
},
{
id: 2,
name: "7折超市优惠券",
price: "70",
originalPrice: "100",
couponId: 2,
}, {
id: 3,
name: "5折餐饮优惠券",
price: "50",
originalPrice: "100",
couponId: 1,
}]
结果: