js如何將一維數(shù)組變成多維數(shù)組

前言

在編程的大多數(shù)情況下我們的需求都是將數(shù)組扁平化進(jìn)行降維,但是確實有那么些情況是要我們將數(shù)組進(jìn)行在分類,從而要升維的。比如,我們獲取了聯(lián)系人數(shù)據(jù),但是我們需要將聯(lián)系人按照字母進(jìn)行分組。針對聯(lián)系人的例子,我們來實地演習(xí)下如何升維數(shù)組。

例子

比如我們有如下數(shù)據(jù),我們需要將下列數(shù)組中以id中的首字母進(jìn)行分類

[
    {"fristCap":"A","id":"Anni","contact":"112123","value":"111"},
    {"fristCap":"A","id":"Aidai","contact":"22222","value":"11111"},
    {"fristCap":"B","id":"Bobo","contact":"22222","value":"25462"},
    {"fristCap":"B","id":"Big","contact":"2222221","value":"23131"},
    {"fristCap":"C","id":"Ca","contact":"322222","value":"2315432"},
]

也就是轉(zhuǎn)換成下面這個樣子:

[
    {
        '"firstCap":"A"
        "data": [
            {"fristCap":"A","id": "Anni", "contact": "112123", "value": "111"},
            { "fristCap":"A","id": "Aidai", "contact": "22222", "value": "11111"}
        ]
    },
    {
        "firstCap": "B",
        "data": [
            {"fristCap":"B", "id": "Bobo",  "contact": "22222", "value": "25462" },
            { "fristCap":"B","id": "Big", "contact": "2222221", "value": "23131"},
        ]
    },
    {
        "firstCap": "C",
        "data": [
            {"fristCap":"C","id": "Ca", "contact": "322222", "value": "333333" }
        ]
    }
]

做法

觀察上面需要轉(zhuǎn)換的數(shù)據(jù)格式,我們的思路是這樣子的,
1、創(chuàng)建一個新的數(shù)組,用來返回歸類好的數(shù)據(jù);
2,創(chuàng)建一個對象,用來標(biāo)記首字母,該對象要有一個標(biāo)記首字母的字段firstCap,還要有一個data字段用來接納相同首字母的數(shù)據(jù)。
3,將新建的數(shù)組用字母升序的方式重新排列

let tempArray = [];//創(chuàng)建一個新數(shù)組
let hash = {};
for (let contact of this.contacts) {
    if(!hash[contact.firstCap]) {
         tempArray.push({firstCap:contact.firstCap,data:[contact]});
         hash[contact.firstCap] = contact;
     } else {
          for(let newContact of tempArray) {
               if (newContact.firstCap === contact.firstCap) {
                     newContact.data.push(contact);
                      break;
                }
           }
      }
  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容