如何将对象分成较小的对象

时间:2018-11-13 17:10:00

标签: javascript ecmascript-6

目标是将长度和形状未知的物体分解成每个3个元素的小物体。只有香草JS解决方案;我不想使用_.pick等。

大对象示例:

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

具有3个键的所需块:

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

3 个答案:

答案 0 :(得分:1)

好,所以这可能不是最有效的方法,但是它可以在我的盒子上使用。 ;)

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

答案 1 :(得分:1)

基于注释,似乎您实际上正在寻找一种将对象分解为几个较小对象的方法。我会这样处理:

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

答案 2 :(得分:0)

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