美文网首页
js如何将一维数组变成多维数组

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

作者: 糖醋里脊120625 | 来源:发表于2019-11-23 14:29 被阅读0次
    [
        {"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;
                    }
               }
          }
      }
    

    相关文章

      网友评论

          本文标题:js如何将一维数组变成多维数组

          本文链接:https://www.haomeiwen.com/subject/vqjhwctx.html