數組中對象屬性名相同歸類處理

這是我最近做的H5 項目,遇到的一些問題,給自己做個筆記
首先頁面結構是這樣的
在這裏插入圖片描述
正常的話渲染頁面後臺返回數據爲二維數組的話會方便多,但是後臺以對象形式返給我
在這裏插入圖片描述

1.問題1 將拿到的數據處理成二維數組

    let arr1 = []
    for(var key in data.records) { //data.records爲拿到的數據對象
         let time = (new Date(key +'-01')).getTime() //爲了排序處理了返回的年月
         let obj = {
            'month':key,
            'date':time,
            'data':data.records[key]
         }
         arr1.push(obj)
     }

正常情況下將arr1 賦值給初始化 的數組就可以渲染,但是發現 for in遍歷對象後,得到的數組並沒有按年月的順序排列即
在這裏插入圖片描述
按照需求,我們展示需要倒序,即最近的月份放上面,於是我進行了排序,根據年月日時間戳的大小排序,

 arr1.sort(this.compare("date")); //排序
 
 // 對數組進行排序(根據返回月份倒序)
  compare (name){  
   return function(o, p){  
     var a, b;  
     if (typeof o === "object" && typeof p === "object" && o && p) {  
         a = o[name];  
         b = p[name];  
         if (a === b) {  
          return 0;  
         }  
         if (typeof a === typeof b) {  
          return a > b ? -1 : 1;   // 如果正序的話 return a < b ? -1 : 1
         }  
         return typeof a > typeof b ? -1 : 1;  // 如果正序的話 return typeof a < typeof b ? -1 : 1;
     } else {  
         throw ("error");  
     }  
     }  
  },

這樣就得到了由近到遠的順序了

2.處理好的數組就可以渲染了,因爲分頁要處理下,在加載第一頁時正常賦值,但是在第N頁時,我這邊做了處理,因爲每頁10條數據,請求回來第二頁數據時我們要將數組按照年月區分歸類,與前面一頁合併

if(that.page == 1) { //加載第一頁數據
    that.dataList = arr1
     }else {//加載第n頁數據
        let newArr= that.dataList.concat(arr1) //先合再歸類  
        var mapObj = {},tempList = [];
        newArr.forEach((item,index) => {  //合併數組
          let ai = item
          if(!mapObj[ai.month]) {
             tempList.push({
         month: ai.month,
                 data: ai.data,
        });
             mapObj[ai.month] = ai;
          }else {
            for(var j = 0; j < tempList.length; j++){
        var dj = tempList[j];
        if(dj.month == ai.month){
          dj.data=dj.data.concat(ai.data)
          break;
        }
       } 
         }
         })
   that.dataList = tempList
}

處理前後的變化
在這裏插入圖片描述

處理後:
在這裏插入圖片描述
好了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章