1. 程式人生 > >javascript之陣列和物件的資料結構轉換

javascript之陣列和物件的資料結構轉換

最近學到物件和陣列的相關知識,將遇到的兩道較複雜的練習題貼出來 

var scoreObject = {
    "Tony": {
        "Math": 95,
        "English": 79,
        "Music": 68
    },
    "Simon": {
        "Math": 100,
        "English": 95,
        "Music": 98
    },
    "Annie": {
        "Math": 54,
        "English": 65,
        "Music": 88
    }
};

以上是一個含有比較規則子物件的物件,要將它轉換為二維陣列,以下是程式碼

// 物件轉化為陣列
function obj2array() {
    var oArray1=[];
    for(var el in scoreObject){
        var oArray=[];
            oArray.push(el);
            var obj = scoreObject[el];
            for(var childEl in obj) {//el為字串
                oArray.push(obj[childEl]);
        }
        oArray1.push(oArray);
    }
    console.log(oArray1);
}
obj2array();
輸出結果為[["Tony", 95, 79, 68],["Simon", 100, 95, 98],["Annie", 54, 65, 88]]

看過了物件轉化為陣列,再來看陣列轉化為物件,如下是例項陣列,這是一個二維陣列(準確地說這是含有子陣列的一維陣列,因為js中沒有
所謂的之說)
var menuArr = [
    [1, "Area1", -1],
    [2, "Area2", -1],
    [3, "Area1-1", 1],
    [4, "Area1-2", 1],
    [5, "Area2-1", 2],
    [6, "Area2-2", 2],
    [7, "Area1-2-3", 4],
    [8, "Area2-2-1", 6],
];

程式碼如下:

//陣列轉化為物件
function array2obj(){
    var menuObject = {};
    //定義以下四個空物件用於存放不同的子物件,實屬無奈之舉
    var subMenu1 = {};
    var subMenu2 ={};
    var subMenu3 = {};
    var subMenu4 = {};
    for(var arr in menuArr){
        var array = menuArr[arr];
        switch (array[2]) {
            case -1:
                var index;
                index = array[0];
                menuObject[index] = {
                    "name": array[1],
               };break;
            case 1:
                subMenu1[array[0]] = {
                    "name":array[1],
                };
                menuObject[array[2]].subMenu = subMenu1;
                break;
            case 2:
                subMenu2[array[0]] = {
                    "name":array[1],
                };
                menuObject[array[2]].subMenu = subMenu2;
                break;
            case 4:
                subMenu3[array[0]] = {
                    "name":array[1],
                };
                subMenu1[array[2]].subMenu = subMenu3;
                break;
            case 6:
                subMenu4[array[0]] = {
                    "name":array[1],
                };
                subMenu2[array[2]].subMenu = subMenu4;
                break;
            default:
                break;
        }
    }
    console.log(menuObject);
}
array2obj();

這種方法有點複雜,若有簡單方法請多多指教