2015-10-20 67 views
0

隨着值的嵌套數組:(JavaScript)的減少和Unflatten陣列

var stagedArray = [ 
    ["Spring", "Volleyball", "V"], 
    ["Spring", "Baseball", "V"], 
    ["Fall", "Baseball", "JV"], 
    ["Fall", "Baseball", "V"] 
]; 

假設分層定位每個嵌套數組的零是父,位置之一是其直接子和兩個位置是位置的子一個,我可以用什麼方法來減少和unflatten這個數組來得到類似這樣的結果:

var finalList = [ 
    { 
     season: "Spring", 
     items: [ 
       { 
        sport: "Basketball", 
        items: [ 
          { division: "V" }, 
         ] 
       } 
       { 
        sport: "Volleyball", 
        items: [ 
          { division: "V" }, 
         ] 
       } 
     ] 
    }, 
     { 
     season: "Fall", 
     items: [ 
       { 
        sport: "Baseball", 
        items: [ 
          { division: "V" }, 
          { division: "JV" } 
         ] 
       } 
     ] 
    }] 

理想的路線,我想創建一個函數來定義什麼位置和標籤關聯到他們動態。 非常感謝!

+2

什麼方法?循環訪問數組並根據需要構建結果。 – Jon

回答

0

在一個良好的起點上與一位同事一起工作,接下來的步驟是更新這個函數遞歸地工作,具有不同的深度和動態標籤。

function getTranformedData(data) { 
    var transformedData = {}; 

    for (var i = 0, n = stagedArray.length; i < n; i++) { 
    var sportData = stagedArray[i]; 

    var season = sportData[0]; 
    var typeOfSport = sportData[1]; 
    var teamDivision = sportData[2]; 

    if (!transformedData.hasOwnProperty(season)) { 
     // Create new season object 
     transformedData[season] = { 
     'season': season, 
     'items': [] 
     }; 
    } 

    var transformedSportData = { 
     'sport': typeOfSport, 
     'items': { 
     'division': teamDivision 
     } 
    }; 

    transformedData[season]['items'].push(transformedSportData); 
    } 
    return transformedData; 
} 

function convertObjectToArrayOfOjects(dataObject) { 
    var data = [] 
    for (var key in dataObject) { 
    data.push(dataObject[key]); 
    } 

    return data; 
} 

var stagedArray = [ 
    ["Spring", "Volleyball", "V"], 
    ["Spring", "Baseball", "V"], 
    ["Fall", "Baseball", "JV"], 
    ["Fall", "Baseball", "V"] 
]; 

var data = getTranformedData(stagedArray); 
data = convertObjectToArrayOfOjects(data); 


console.log(data); 


/* RESULTING DAT STRUCTURE */ 

/* 

[{ 
    "season": "Spring", 
    "items": [{ 
    "sport": "Volleyball", 
    "items": { 
     "division": "V" 
    } 
    }, { 
    "sport": "Baseball", 
    "items": { 
     "division": "V" 
    } 
    }] 
}, { 
    "season": "Fall", 
    "items": [{ 
    "sport": "Baseball", 
    "items": { 
     "division": "JV" 
    } 
    }, { 
    "sport": "Baseball", 
    "items": { 
     "division": "V" 
    } 
    }] 
}] 


*/