How to chunk an object into smaller objects

2020-05-03 01:10发布

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:

const data = {
    someFirstKey: 'someFirstVal',
    someSecondKey: 'someSecondVal',
    ...
    someLastKey: 'someLastVal'
}

Desired chunk with 3 keys:

{someKey0: 'someVal0', someKey1: 'someVal1', someKey2, 'someVal2'}

3条回答
叛逆
2楼-- · 2020-05-03 01:42

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));
查看更多
仙女界的扛把子
3楼-- · 2020-05-03 01:44

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

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

const 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);
}
查看更多
该账号已被封号
4楼-- · 2020-05-03 01:48

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

查看更多
登录 后发表回答