2013-01-16 104 views
1

如何將兩個數組轉換爲對象?javascript數組和對象

我的數組:

arr1.push(3,2,3,6,11,7);   
arr2.push("num1","num2","num3","num4","num5","num6"); 

如何將其轉換爲對象:

[{name:"num1", value:3}, {name:"num2", value:2}, {name:"num3", value:3}, {name:"num4", value:6}, {name:"num5", value:11}, {name:"num6", value:7}] 

回答

3

你可以嘗試

var obj = []; 

for(var i = 0; i < arr1.length; i++){ 
    obj[i] = {name : arr1[i], value: arr2[i]}; 
} 
0
var arr = [], 
    cv = -1; 

while(++cv < arr1.length) { 
    arr.push({name:arr2[cv], value:arr1[cv]}); 
} 
0

你基本上有合併這兩個陣列。假設兩個陣列的長度始終相等

arr1.push(3,2,3,6,11,7);   
arr2.push("num1","num2","num3","num4","num5","num6"); 

var obj = [], i; 
for(i=0; i<l; i++) { 
    obj.push(arr1[i]+":"+arr2[i]); 
} 
// obj is now required object