原始效果:
目标效果:相同名称的数量进行累加
this.list数据
[
{
id: "1",
name: "霸王几盒3",
num: 1,
}, {
id: "2",
name: "霸王几盒3",
num: 1,
}, {
id: "3",
name: "我是小白",
num: 1,
}, {
id: "4",
name: "霸王几盒3",
num: 1,
},
]
操作代码(思路:循环找到一样名称的然后进行累加)
// 定义局部变量,用来操作
let detailedList = [];
// 用于储存临时数据(记录)
let tmp = {};
// this.list是我们的数组数据
this.list.forEach((v) => {
if (!tmp.hasOwnProperty(v.name)) {
tmp[v.name] = detailedList.length;
return detailedList.push(Object.assign({}, v));
}
detailedList[tmp[v.name]].num += v.num;
});
// 赋值(这时你打印detailedList,就是我们要的目标数据了)
this.formDataChu.listChu = detailedList
最后有什么不懂的欢迎留言,如果能帮助到你,请给我点个赞以示鼓励吧!