将对象拆分为块

时间:2017-09-08 23:07:15

标签: javascript arrays object

我有一个对象:

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}]

我有点被困在这里,因为我无法使用切片

这是我怎么做的,但它很难看。我只是想看看如何以正确的方式做到这一点

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);
    }
}

2 个答案:

答案 0 :(得分:1)

另一个使用Lodash块方法的选项,加上一些ES6,如下所示:

import { chunk } from 'lodash';

const chunkSize = 3;

const arrayFromObject = Object.entries(object).map(([key, value]) => ({ [key]: value }));
const final = chunk(arrayFromObject, chunkSize);

答案 1 :(得分:0)

所以,这是:

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)