我有一个对象:

var object = { '232510350': 672,
'232510352': 672,
'232510353': 672,
'232510356': 672,
'232510358': 672,
'232510359': 672,
'232510360': 672 }

我想将其分成给定大小的块,如下所示:
var chunks = [
{'232510350': 672,
'232510352': 672,
'232510353': 672},
{'232510356': 672,
'232510358': 672,
'232510359': 672},
{'232510360': 672}]

我有点卡在这里,因为我不能为此使用 slice

这是我的操作方式,但是很丑。我只是想看看如何正确地做
var temp = {};
var chunks = [];
var chunkSize = 3;
var amount = chunkSize;

for (var i = 0; i < Object.keys(object).length; i++) {
    if (i == chunkSize) {
        chunks.push(temp);
        chunkSize += amount;
        temp = {};
    }

    temp[ Object.keys(object)[i] ] = object[ Object.keys(object)[i] ];

    if (i == Object.keys(object).length - 1) {
        chunks.push(temp);
    }
}

最佳答案

因此,这里是:

var object = { '232510350': 672,
'232510352': 672,
'232510353': 672,
'232510356': 672,
'232510358': 672,
'232510359': 672,
'232510360': 672 }

var values = Object.values(object);
var final = [];
var counter = 0;
var portion = {};

for (var key in object) {
  if (counter !== 0 && counter % 3 === 0) {
    final.push(portion);
    portion = {};
  }
  portion[key] = values[counter];
  counter++
}
final.push(portion);

console.log(final)

09-25 16:27