小程序開發筆記(八)—Js數組按日期分組顯示數據

數據分組展現有兩種方式,一種是後端直接傳入分組格式的Json數據,另外一種是咱們在前端本身轉換格式,這裏咱們在前端處理轉換按日期分組的數據格式html

一、例如後端返回數據格式爲:前端

[{createtime:'2019-07-29',content:'哈哈哈'},{createtime:'2019-07-29',content:'哈哈哈'}]

二、頁面展現須要的格式爲:mysql

[{createtime:'2019-07-29',list:[{createtime:'2019-07-29',content:'哈哈哈'},{createtime:'2019-07-29',content:'哈哈哈'}]}]

三、下面咱們使用Js處理成按日期分組歸類的數據,代碼以下:git

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);
          }
    })

四、處理後的結果:sql

[
    {
        "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
http://www.javashuo.com/article/p-gmdrskit-ku.htmlpost

相關文章
相關標籤/搜索