2014-11-22 67 views
0

所以我有一個棘手的問題的一點就在這裏:合併陣列對象和對象數組

我得到5×2陣列從這個函數

for (var i = 0; i < 5; i++) { 
    var name = $('.lesson-space:eq(' + i + ') > .lesson').map(function(){return $(this).data('name');}).get(); 
    var color = $('.lesson-space:eq(' + i + ') > .lesson').map(function(){return $(this).data('color');}).get(); 
    }; 

對於每5次重複我想要將這兩個陣列放入這樣的對象中

 { 
     "name": "deutsch", 
     "color": "red" 
     }, 
     { 
     "name": "mathe", 
     "color": "blue" 
     }, 
     { 
     "name": "sport", 
     "color": "darkblue" 
     }, 
     { 
     "name": "franz", 
     "color": "yellow" 
     } 

這些對象現在應放入數組中。所以,最後我想有5門陣列(剪斷,從第一個代碼)放進一個數組這樣

[ 
[ 
    ... 
],[ 
    ... 
],[ 
    ... 
],[ 
    ... 
],[ 
    ... 
] 

]

我知道這是一個有點複雜......

+0

下劃線或LO-儀表將能夠幫助你實現這個更容易..如果你不介意依賴關係添加。 – RadleyMith 2014-11-22 15:03:02

+0

也爲什麼你會在對象和數組結構之間來回切換?或者你想把5個對象放在另一個數組內的數組中? – RadleyMith 2014-11-22 15:06:47

回答

1

我瞭解你想要做這樣的事情

var res = [], 
    data = {}; 

for (var i = 0; i < 5; i++) { 

    data = $('.lesson-space:eq(' + i + ') > .lesson').map(function() { 
    var name = $(this).data('name'); 
    var color = $(this).data('color'); 

    if (!name || !color) { 
     return null; 
    } 

    return { 
     name: name, 
     color: color 
    } 
    }).get(); 

    res.push(data); 
} 
0

這應該工作

var mainArray = []; 

for (i = 0; i < name.length; i++) { 
    var o = {}; 
    o.name = name[i]; 
    o.color = color[i]; 
    mainArray.push([o]) 
} 
1

我不知道我理解正確的話,你的要求,但我認爲這是你在找什麼

var result = []; 
for (var i = 0; i < 5; i++) { 
    result.push($('.lesson-space:eq('+i+') > .lesson').get().map(function(){ 
     return { 
      name: $(this).data('name'), 
      color: $(this).data('name') 
     }; 
    })); 
} 

console.log(result); 
+0

你必須把.get()放在最後:) – brighthero 2014-11-22 16:05:41