需求: 数组对象,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处理逻辑:文章来源:https://www.toymoban.com/news/detail-824271.html
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,要不会导致合并之后的数据值不对文章来源地址https://www.toymoban.com/news/detail-824271.html
到了这里,关于数组对象,名字相同的对象进行合并的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!