需求: 数组对象,name字段相同的进行合并,并将每条数据中的num累加,金额为合并之后的num*price
原始数据tableData
<el-table
:data="tableData"
style="width: 100%; margin-bottom: 20px"
border
>
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="num" label="数量"></el-table-column>
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="price" label="单价"></el-table-column>
</el-table>
const tableData = reactive([
{ date: '2023-10-13',num: 30,name: '零食',price: 20, },
{ date: '2023-12-23',num: 15,name: '干果',price: 56 },
{ date: '2023-5-16',num: 50,name: '零食',price: 20 },
{ date: '2023-8-21',num: 22,name: '干果',price: 56 },
{ date: '2023-8-21',num: 22,name: '货物',price: 26 },
{ date: '2023-9-12',num: 10,name: '衣服',price: 26 },
])
现在需要将数据合并为以下展示形式:日期进行合并为多个数据合并之前的日期区间
<el-table
:data="newData"
style="width: 100%; margin-bottom: 20px"
border
>
<el-table-column prop="date" label="日期"></el-table-column>
<el-table-column prop="num" label="数量"></el-table-column>
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="amount" label="金额"></el-table-column>
</el-table>
js处理逻辑:
const newData = ref([])
const getData = ()=>{
let temp = {}
let start_date = ''
let end_date = ''
for(var i=0;i<tableData.length;i++){
let item = tableData[i]
let {name,date,price,num} = item
if(temp[name] == null){
temp[name] = JSON.parse(JSON.stringify(item))
temp[name]['amount'] = num * price
start_date = date.replace(/-/g, '')
end_date = date.replace(/-/g, '')
}else{
item = JSON.parse(JSON.stringify(item))
temp[name]['num'] += num
temp[name]['amount'] += num * price
end_date = date.replace(/-/g, '')
}
let dateRage = [start_date,end_date]
const newDateRange = dateRage.filter((item)=>item != '')
newDateRange.sort((a,b)=>{
return new Date(a) - new Date(b)
})
temp[name]['date'] = newDateRange[0] + '-' + newDateRange[newDateRange.length - 1]
}
let newArr = []
Object.keys(temp).forEach(item=>{
newArr.push(temp[item])
})
newData.value = newArr
}
需要注意:temp[name] = JSON.parse(JSON.stringify(item))需要使用深copy,要不会导致合并之后的数据值不对
日期的处理是有问题的,日期的要求是合并之后日期按照从小到大的顺序,如果日期相同就展示当前日期-当前日期,改造了下对日期的处理,其他代码不变,只对日期做处理
for(var i=0;i<tableData.length;i++){
let item = tableData[i]
let {name,date,price,num} = item
if(temp[name] == null){
temp[name] = JSON.parse(JSON.stringify(item))
temp[name]['amount'] = num * price
temp[name]['newDate'] = [date]
}else{
item = JSON.parse(JSON.stringify(item))
temp[name]['num'] += num
temp[name]['amount'] += num * price
temp[name]['newDate'].push(date)
}
let dateRage = temp[name]['newDate']
const newDateRange = dateRage.filter((item)=>item != '')
newDateRange.sort((a,b)=>{
return new Date(a) - new Date(b)
})
temp[name]['date'] = newDateRange[0].replace(/-/g, '') + '-' + newDateRange[newDateRange.length - 1].replace(/-/g, '')
}