How to chunk an object into smaller objects











up vote
0
down vote

favorite












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









share|improve this question




















  • 1




    @VonAxt If the order of the items being returned is important, then the data should not be formatted as an object, but rather an array. If you always want the keys to be sorted alphabetically as in your example, that makes things easier - you can pull out the keys, sort them, and get their values in order.
    – Tyler Roper
    Nov 13 at 17:18






  • 1




    @VonAxt Object keys do not have positions.
    – Tyler Roper
    Nov 13 at 17:21






  • 2




    So wait, your goal is to break an object up into several smaller objects, but you don't care how it gets broken up as long as each small object has at most 3 keys?
    – Paulpro
    Nov 13 at 17:22






  • 1




    This looks like a homework problem. I can't imagine any valid business case for breaking an arbitrary data structure into smaller arbitrary data structures without knowing how they fit together or can get deserialized reliably.
    – Paul
    Nov 13 at 17:27






  • 1




    @VonAxt I agree w/ everyone else, this is a far better case for an array than an object. But see my answer.
    – Paul
    Nov 13 at 17:56















up vote
0
down vote

favorite












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









share|improve this question




















  • 1




    @VonAxt If the order of the items being returned is important, then the data should not be formatted as an object, but rather an array. If you always want the keys to be sorted alphabetically as in your example, that makes things easier - you can pull out the keys, sort them, and get their values in order.
    – Tyler Roper
    Nov 13 at 17:18






  • 1




    @VonAxt Object keys do not have positions.
    – Tyler Roper
    Nov 13 at 17:21






  • 2




    So wait, your goal is to break an object up into several smaller objects, but you don't care how it gets broken up as long as each small object has at most 3 keys?
    – Paulpro
    Nov 13 at 17:22






  • 1




    This looks like a homework problem. I can't imagine any valid business case for breaking an arbitrary data structure into smaller arbitrary data structures without knowing how they fit together or can get deserialized reliably.
    – Paul
    Nov 13 at 17:27






  • 1




    @VonAxt I agree w/ everyone else, this is a far better case for an array than an object. But see my answer.
    – Paul
    Nov 13 at 17:56













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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









share|improve this question















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






javascript ecmascript-6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 at 18:42









Paulpro

111k15221229




111k15221229










asked Nov 13 at 17:09









VonAxt

576




576








  • 1




    @VonAxt If the order of the items being returned is important, then the data should not be formatted as an object, but rather an array. If you always want the keys to be sorted alphabetically as in your example, that makes things easier - you can pull out the keys, sort them, and get their values in order.
    – Tyler Roper
    Nov 13 at 17:18






  • 1




    @VonAxt Object keys do not have positions.
    – Tyler Roper
    Nov 13 at 17:21






  • 2




    So wait, your goal is to break an object up into several smaller objects, but you don't care how it gets broken up as long as each small object has at most 3 keys?
    – Paulpro
    Nov 13 at 17:22






  • 1




    This looks like a homework problem. I can't imagine any valid business case for breaking an arbitrary data structure into smaller arbitrary data structures without knowing how they fit together or can get deserialized reliably.
    – Paul
    Nov 13 at 17:27






  • 1




    @VonAxt I agree w/ everyone else, this is a far better case for an array than an object. But see my answer.
    – Paul
    Nov 13 at 17:56














  • 1




    @VonAxt If the order of the items being returned is important, then the data should not be formatted as an object, but rather an array. If you always want the keys to be sorted alphabetically as in your example, that makes things easier - you can pull out the keys, sort them, and get their values in order.
    – Tyler Roper
    Nov 13 at 17:18






  • 1




    @VonAxt Object keys do not have positions.
    – Tyler Roper
    Nov 13 at 17:21






  • 2




    So wait, your goal is to break an object up into several smaller objects, but you don't care how it gets broken up as long as each small object has at most 3 keys?
    – Paulpro
    Nov 13 at 17:22






  • 1




    This looks like a homework problem. I can't imagine any valid business case for breaking an arbitrary data structure into smaller arbitrary data structures without knowing how they fit together or can get deserialized reliably.
    – Paul
    Nov 13 at 17:27






  • 1




    @VonAxt I agree w/ everyone else, this is a far better case for an array than an object. But see my answer.
    – Paul
    Nov 13 at 17:56








1




1




@VonAxt If the order of the items being returned is important, then the data should not be formatted as an object, but rather an array. If you always want the keys to be sorted alphabetically as in your example, that makes things easier - you can pull out the keys, sort them, and get their values in order.
– Tyler Roper
Nov 13 at 17:18




@VonAxt If the order of the items being returned is important, then the data should not be formatted as an object, but rather an array. If you always want the keys to be sorted alphabetically as in your example, that makes things easier - you can pull out the keys, sort them, and get their values in order.
– Tyler Roper
Nov 13 at 17:18




1




1




@VonAxt Object keys do not have positions.
– Tyler Roper
Nov 13 at 17:21




@VonAxt Object keys do not have positions.
– Tyler Roper
Nov 13 at 17:21




2




2




So wait, your goal is to break an object up into several smaller objects, but you don't care how it gets broken up as long as each small object has at most 3 keys?
– Paulpro
Nov 13 at 17:22




So wait, your goal is to break an object up into several smaller objects, but you don't care how it gets broken up as long as each small object has at most 3 keys?
– Paulpro
Nov 13 at 17:22




1




1




This looks like a homework problem. I can't imagine any valid business case for breaking an arbitrary data structure into smaller arbitrary data structures without knowing how they fit together or can get deserialized reliably.
– Paul
Nov 13 at 17:27




This looks like a homework problem. I can't imagine any valid business case for breaking an arbitrary data structure into smaller arbitrary data structures without knowing how they fit together or can get deserialized reliably.
– Paul
Nov 13 at 17:27




1




1




@VonAxt I agree w/ everyone else, this is a far better case for an array than an object. But see my answer.
– Paul
Nov 13 at 17:56




@VonAxt I agree w/ everyone else, this is a far better case for an array than an object. But see my answer.
– Paul
Nov 13 at 17:56












2 Answers
2






active

oldest

votes

















up vote
1
down vote













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





share|improve this answer






























    up vote
    1
    down vote













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








    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286253%2fhow-to-chunk-an-object-into-smaller-objects%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













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





      share|improve this answer



























        up vote
        1
        down vote













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





        share|improve this answer

























          up vote
          1
          down vote










          up vote
          1
          down vote









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





          share|improve this answer














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






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 13 at 18:55









          Paulpro

          111k15221229




          111k15221229










          answered Nov 13 at 17:56









          Paul

          25.8k75991




          25.8k75991
























              up vote
              1
              down vote













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








              share|improve this answer



























                up vote
                1
                down vote













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








                share|improve this answer

























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









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








                  share|improve this answer














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








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





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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 13 at 22:22

























                  answered Nov 13 at 18:25









                  Paulpro

                  111k15221229




                  111k15221229






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286253%2fhow-to-chunk-an-object-into-smaller-objects%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to change which sound is reproduced for terminal bell?

                      Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                      Can I use Tabulator js library in my java Spring + Thymeleaf project?