數據分組展示有兩種方式,一種是后端直接傳入分組格式的Json數據,另一種是我們在前端自己轉換格式,這里我們在前端處理轉換按日期分組的數據格式
1、例如后端返回數據格式為:
[{createtime:'2019-07-29',content:'哈哈哈'},{createtime:'2019-07-29',content:'哈哈哈'}]
2、頁面展示需要的格式為:
[{createtime:'2019-07-29',list:[{createtime:'2019-07-29',content:'哈哈哈'},{createtime:'2019-07-29',content:'哈哈哈'}]}]
3、下面我們使用Js處理成按日期分組歸類的數據,代碼如下:
let newArr = [];
_list.forEach((item,i)=>{
let index = -1;
let isExists = newArr.some((newItem,j)=>{
if(item.createtime==newItem.createtime){
index = j;
return true;
}
})
if(!isExists){
newArr.push({
createtime:item.createtime,
timeDay:item.timeDay,
timeMonth:item.timeMonth,
subList:[item]
})
}else{
newArr[index].subList.push(item);
}
})
4、處理后的結果:
[
{
"createtime":"2019-07-27",
"timeDay":27,
"timeMonth":7,
"subList":[
{
"group_post_id":128,
"group_id":0,
"group_topic_id":"",
"uid":73,
"nickname":"阿健w ",
"avatar_url":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKicUgL8bc6EDmPcST3ozT00OZTpmJSrpcFaB3Fjfp5b4PWNxEraKu1wviaIicxVcRzxOE7FfLRYFOTg/132",
"content":"哈哈哈",
"longitude":116.340988,
"latitude":40.006805,
"province":"",
"city":"",
"location":"",
"address":"",
"like_count":0,
"comment_count":0,
"status":"0",
"createtime":"2019-07-27",
"pics":[
],
"timeDay":27,
"timeMonth":7
}
]
}]
問題:
以上這種方式處理在正常情況下是沒有問題的,但通常我們在分組顯示的時候會存在分頁的問題,可以看到下圖出現了兩個相同的日期,是因為同一天的分組數據不能一頁展示完,可能會在第二頁或者第三頁出現的情況
解決:
方式1:
參考我之前的一個做法https://www.cnblogs.com/fozero/p/7599785.html
if(pageNum==1){
this.list = newArr;
}else{
// 解決分組分頁問題
// 遍歷newArr 與上頁最后一條記錄日期比較,相同日期則直接追加
for(let i in newArr){
if(newArr[i].createtime==this.list[this.list.length-1].createtime){
this.list[this.list.length-1].subList = this.list[this.list.length-1].subList.concat(newArr[i].subList);
}else{
this.list.push(newArr[i]);//數組追加
}
}
}
方式2:
參考使用后端mysql分組查詢並按照分組條數來進行分頁
https://www.cnblogs.com/jackyfee/archive/2011/05/07/GroupPage.html
https://blog.csdn.net/zhang197093/article/details/49425261