Search code examples
javascriptlodash

Does lodash or vanilla JS have a nice way to flatten an object of arrays into an array?


What I want to do is take an object like

{  SomeKey: [A, B, C], 
   SomeOtherKey: [D], 
   AndAnother: [E, F]  }

and make it into

[ A, B, C, D, E, F ]

I don't see any nice way in the documentation, but maybe it's hiding in plain sight from me.


Solution

  • If you're on the very latest generation of browsers, you may be able to use Object.values, which does exactly what it sounds like:

    const data = {
      SomeKey: ['A', 'B', 'C'],
      SomeOtherKey: ['D'],
      AndAnother: ['E', 'F']
    };
    
    const out = [].concat(...Object.values(data));
    
    console.log(out);

    If you're on slightly older browsers (back to IE9), Object.keys is still pretty close:

    const data = {
      SomeKey: ['A', 'B', 'C'],
      SomeOtherKey: ['D'],
      AndAnother: ['E', 'F']
    };
    
    const out = [].concat(...Object.keys(data).map(key => data[key]));
    
    console.log(out);

    (concat optimization from vlaz's answer edited in at Oriol's suggestion)