HTML
<template>
<div>
<div v-for="item in list">
id:{{item.id}} - count:{{item.count}}
</div>
<br />
<div>点击按钮去重,count叠加</div>
<button @click="getData">去重</button>
</div>
</template>
JavaScript
<script>
export default {
name: 'app',
data(){
return {
list: [
{
id: 0,
count: 2,
},
{
id: 1,
count: 2,
},
{
id: 2,
count: 2,
},
{
id: 3,
count: 2,
},
{
id: 0,
count: 2,
},
{
id: 2,
count: 2,
},
]
}
},
methods: {
getData(){
let listFilter = this.list
// 定义map方法
const res = new Map();
// 过滤器过滤listFilter
this.list = listFilter.filter((item) => {
// res收集第一次存在的元素,如果存在,查看存在的位置,对list中的count进行叠加
if(res.has(item.id)){
for(let [key,value] of res){
if(key==item.id){
this.list[key].count += item.count
}
}
}
// 如果不存在,则添加到res中
return !res.has(item.id) && res.set(item.id, 1)
});
}
}
}
</script>
点击按钮前
点击按钮后