Skip to content Skip to sidebar Skip to footer

How To Chunk An Object Into Smaller Objects

The goal is to break an object of unknown length and shape into small objects 3 elements each. Only vanilla JS solution; I don't want to use _.pick etc. Example of large object: co

Solution 1:

Based on the comments, it seems like you are actually looking for a way to split an object up into several smaller objects. I would approach that like this:

const data = {a:1,b:2,c:3,d:4,e:5,f:6,g:7};

const chunk_size = 3, chunks = [];
for ( const cols = Object.entries( data ); cols.length; )
  chunks.push( cols.splice(0, chunk_size).reduce( (o,[k,v])=>(o[k]=v,o), {}));

console.log( chunks );

Solution 2:

Ok, so this might not be the most efficient way, but it works on my box. ;)

const data = {} // fill in your data hereconst keys = Object.keys(data); // gets you the keys from your obj. const numberOfWholeParts = Math.floor( keys.length / 3 );  // or whatever your size limit isconst remainder = keys.length % 2; // keys left after all whole parts are filledconst arrayOfParts = [];

for(let i=0;i<numberOfWholeParts;i++) {
   const obj = {};
   const keySegment = keys.slice(i*3, i*3+3);

   for(let j=0; j<3; j++) {
     obj[keySegment[j]] = data[keySegment[j]];
   }
   arrayOfParts.push(obj);
} 
if(remainder > 0){
  const obj = {};
  let remainingKeys = keys.slice(-remainder)
  for(let i=0; i<remainingKeys.length;i++) {
    obj[remainingKeys[i]] = data[remainingKeys[i]];
  }
  arrayOfParts.push(obj);
}

Solution 3:

Using Object.fromEntries:

const entries = Object.entries(data);
const grouped = [];

for (let i = 0; i < entries.length; i++) {
    if (i % groupSize === 0) {
        grouped.push([entries[i]]);
    } else {
        grouped[Math.floor(i / groupSize)].push(entries[i]);
    }
}

const chunks = grouped.map(o =>Object.fromEntries(o));

Post a Comment for "How To Chunk An Object Into Smaller Objects"