前言
在編程的大多數(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;
}
}
}
}