2

我有以下许多对象的 JavaScript 数组:

[
    {...},
    {...},
    {...},
    .
    .
    .
    .
    .
    {...},
    {...}
]

我想将数组转换为 3 个对象的行,如下所示:

[
    [ {...}, {...}, {...} ],
    [ {...}, {...}, {...} ],
    [ {...}, {...}, {...} ],
    .
    .
    .
    [ {...}, {...}, {...} ],
    [ {...}, {...}, {...} ]
]

最好的方法是什么?

4

4 回答 4

3

另一个片段(改编自@Florent)

var result = [];

do {
   result.push( data.splice( 0, 3 ) )
} while( data.length );
于 2012-10-23T15:24:11.463 回答
2

使用for循环:

var i = 0
  , n = data.length
  , result = [];

for (; i < n; i += 3) {
  result.push([data[i], data[i + 1], data[i + 2]]);
}
于 2012-10-23T15:17:34.660 回答
2

你可以用一个循环来做到这一点。这需要数组items并创建数组result

var result = [];
var line;
for (var i = 0; i < items.length; i++) {
  if (i % 3 == 0) {
    line = [];
    result.push(line);
  }
  line.push(items[i]);
}

(即使源数组不能被三整除,这种循环方式也有效。)

于 2012-10-23T15:18:06.203 回答
0

只是另一种选择:)

var result = arr.reduce(
    function(prev, curr, index) { 
        if(index > 1) { 
            if(prev[prev.length-1].length == 3) 
                prev.push([]); 
            prev[prev.length-1].push(curr); 
            return prev; 
        }
        return [[prev, curr]]; 
    }
);
于 2012-10-23T15:51:19.460 回答