I have an object:
var object = { '232510350': 672,
'232510352': 672,
'232510353': 672,
'232510356': 672,
'232510358': 672,
'232510359': 672,
'232510360': 672 }
And I want to split it into chunks of a given size like this:
var chunks = [
{'232510350': 672,
'232510352': 672,
'232510353': 672},
{'232510356': 672,
'232510358': 672,
'232510359': 672},
{'232510360': 672}]
I'm kinda stuck here since I can't use slice for this
Here's how I did it but it's ugly. I just wanted to see how to do it the right way
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);
}
}
So, here it is:
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)
Another option using the Lodash chunk method, plus some ES6 would be as follows:
import { chunk } from 'lodash';
const chunkSize = 3;
const arrayFromObject = Object.entries(object).map(([key, value]) => ({ [key]: value }));
const final = chunk(arrayFromObject, chunkSize);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With