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
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With