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") 

それらを保存し、4つのアイテムとしてグループ化したい..私の配列がこのようになるように

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

  }
4

4 に答える 4

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]};
        })
    });
}
于 2012-10-26T03:13:50.863 に答える
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);
于 2012-10-26T03:26:47.403 に答える
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]};
                      })
                   });
}, []);
于 2012-10-26T03:35:47.477 に答える
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)
    });
}
于 2012-10-26T03:08:59.897 に答える