2012-10-26 136 views
0

集合返回如下11項;創建正確的陣列結構

(1, "Ball", "Result1") 
    (2, "Ball", " Result2") 
    (3, "Ball", " Result3") 
    (4, "Ball", " Result4") 
    (5, "Ball", " Result5") 
    (6, "Ball", " Result6") 
    (7, "Ball", " Result7") 
    (8, "Ball", " Result8") 
    (9, "Pool", " Pool 1") 
    (10, "Pool", " Pool 2") 
    (11, "Pool", " Pool 3") 

我想存儲它們,將它們作爲組四個項目。所以,我的陣列看起來像這樣

var data = []; 
        data.push({ 
        myclass: "First4", 
        schedule: [ { 
         id : '1', 
         gameType: 'Ball', 

         result: 'Result11' 
        }, { 
         id: '2', 
         gameType: 'Ball', 

         result: 'Result2' 

        },........... ] 



       }); 
            //second group 
       data.push({ 
        divClass : "second4", 
        items : [ { 
         id : '5' 
         gameType: 'Ball', 
         result: 'Result5' 
        }, { 
         id : '' 
         gameType: 'Ball', 
         result: 'Result6 

        } ] 
       }); 

我怎麼可以寫一個for循環,這樣我可以動態地達到同樣的效果而不是寫推手動

for(var i = 0; i < collLength; i++){ 
// do push 1 with first four //data.push(class, sheculde first 4 items, result) 
// do second push with second four 
// do third push with the remaining 

    } 
+0

你是否真的想給你的類命名爲「first4」,「second4」等?通過數組索引動態分類「group0」,「group1」等等,其中數字來自數組索引似乎更簡單。 –

+0

...但是對於你的循環,只要將'i ++'改成'i + = 4',然後在[i],'i + 1','i + 2','i + 3'循環。 –

+0

我只是想清楚我的問題......我需要做的是,當我收到x個項目時,在這種情況下,我希望有x個小組(在這種情況下是3個),其中每個小組最多可容納4件物品。我只是不能寫出循環的權利動態地執行它...... – myTD

回答

1
var data = []; 

for(var i = 0; i < collLength; i+=4) { 
    data.push({ 
     divClass: "group" + (i/4), 
     items: collection.slice(i, i + 4).map(function(item) { 
      return {id:item[0], gameType:item[1], result:item[2]}; 
     }) 
    }); 
} 
+0

下面是一個演示:http://jsfiddle.net/N4hS3/ –

+0

謝謝...... jsfiddle的例子太.. – myTD

+0

不客氣。 –

0
var indata = [...]; // this is filled with your list of objects. 
var outdata = [ ]; 

var n = indata.length; 

for (var i = 0; i < n; i += 4) 
{ 
    outdata.push({ 
     class: 'group' + outdata.length, 
     items: indata.slice(i, i + 4) 
    }); 
} 
0
var indata = [...]; // this is filled with your list of objects. 
var outdata = [ ]; 

function mapper(element, i) 
{ 
    var j = Math.floor(i/4); 

    if (outdata[j] == undefined) 
     outdata[j] = { class: 'group' + j, items: [ ] }; 

    outdata[j].items.push(element); 
} 

indata.map(mapper); 
0

以下是使用.reduce()的方法。

var data = collection.reduce(function(arr, obj, i) { 
    return i % 4 ? arr : 
        arr.concat({ 
         divClass: "group" + (i/4), 
         items: collection.slice(i, i + 4).map(function(item) { 
          return {id:item[0], gameType:item[1], result:item[2]}; 
         }) 
        }); 
}, []); 
+0

演示:http://jsfiddle.net/N4hS3/1/ –