js如何将一维数组变成多维数组

2019-11-23  本文已影响0人  糖醋里脊120625
[
    {"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"},
]

//也就是转换成下面这个样子:
[
    {
        '"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" }
        ]
    }
]
let tempArray = [];//创建一个新数组
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;
                }
           }
      }
  }
上一篇下一篇

猜你喜欢

热点阅读