编码
学习通用的数据用不同的数据结构进行存储,以及相互的转换
对象转为数组:
var scoreObject = {
"Tony": {
"Math": 95,
"English": 79,
"Music": 68
},
"Simon": {
"Math": 100,
"English": 95,
"Music": 98
},
"Annie": {
"Math": 54,
"English": 65,
"Music": 88
}
}
如上有一个用来存储学习成绩的对象,编写一个函数,将其转为如下的二维数组
var scoreArray = [
["Tony", 95, 79, 68],
……
];
数组转为对象:
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],
];
如上有一个用来存储多级菜单数据的数组,编写一个函数,将其转为如下的对象
var menuObject = {
"1": {
name: "Area1",
subMenu: {
"3": {
name: "Area1-1"
},
"4": {
name: "Area1-2",
subMenu: {
"7": {
name: "Area1-2-3"
}
}
}
}
}
……
}
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="utf-8" /> 6 <title>JS里的居民们9-对象和数组转换</title> 7 </head> 8 9 <body> 10 <script> 11 //对象转数组 12 var scoreObject = { 13 "Tony": { 14 "Math": 95, 15 "English": 79, 16 "Music": 68 17 }, 18 "Simon": { 19 "Math": 100, 20 "English": 95, 21 "Music": 98 22 }, 23 "Annie": { 24 "Math": 54, 25 "English": 65, 26 "Music": 88 27 } 28 } 29 var arr1 = []; 30 for (var i in scoreObject) { 31 var arr2 = []; 32 arr2.push(i); 33 for (var j in scoreObject[i]) { 34 arr2.push(scoreObject[i][j]); 35 } 36 arr1.push(arr2); 37 } 38 console.log(arr1); 39 //数组转对象 40 var menuArr = [ 41 [1, "Area1", -1], 42 [2, "Area2", -1], 43 [3, "Area1-1", 1], 44 [4, "Area1-2", 1], 45 [5, "Area2-1", 2], 46 [6, "Area2-2", 2], 47 [7, "Area1-2-3", 4], 48 [8, "Area2-2-1", 6], 49 ]; 50 51 var menuObject = {}; 52 menuArr.forEach((current, index) => { 53 if (current[2] == -1) { 54 menuObject[current[0]] = { 55 "name": current[1], 56 "subMenu": {} 57 } 58 } 59 if (current[2] == 1) { 60 menuObject["1"]["subMenu"][current[0]] = { 61 "name": current[1], 62 "subMenu": {} 63 } 64 } 65 if (current[2] == 2) { 66 menuObject["2"]["subMenu"][current[0]] = { 67 "name": current[1], 68 "subMenu": {} 69 } 70 } 71 if (current[2] == 4) { 72 menuObject["1"]["subMenu"]["4"]["subMenu"][current[0]] = { 73 "name": current[1], 74 "subMenu": {} 75 } 76 } 77 if (current[2] == 6) { 78 menuObject["2"][ "subMenu"]["6"]["subMenu"][current[0]] = { 79 "name": current[1], 80 "subMenu": {} 81 } 82 } 83 }) 84 console.log(menuObject); 85 </script> 86 </body> 87 88 </html>