Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten arrays in an object

Tags:

javascript

I have an object as below:

const USER_MAP = {
  PREMIUM: ['a', 'b'],
  RETAIL: ['c', 'd']
};

I would like to transform to below

[
  { segment: 'PREMIUM', id: 'a' },
  { segment: 'PREMIUM', id: 'b' },
  { segment: 'RETAIL', id: 'c' },
  { segment: 'RETAIL', id: 'd' }
]

I came up with a solution as below

const USER_MAP = {
  PREMIUM: ['a', 'b'],
  RETAIL: ['c', 'd']
};


const userList = Object.entries(USER_MAP).reduce((accumulator, currentValue) => {
   const userListByType = currentValue[1].map(id => ({ id, segment: currentValue[0]}))
  return [...accumulator, ...userListByType]
}, []);

console.log(userList);

It works but im wondering if there might be a better way to achieve above? In terms of readability as I'm nesting a map in a reduce, it seems to me that I might've complicated stuffs here

like image 849
Isaac Avatar asked Mar 27 '26 06:03

Isaac


1 Answers

You could take Array#flatMap with a mapping of nested objects with outer key.

const
    USER_MAP = { PREMIUM: ['a', 'b'], RETAIL: ['c', 'd'] },
    result = Object
        .entries(USER_MAP)
        .flatMap(([segment, a]) => a.map(id => ({ segment, id })));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 119
Nina Scholz Avatar answered Mar 29 '26 18:03

Nina Scholz