Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"FUNctional" 😜 Map πŸ—Ί to object πŸ”‘
const obj = { a: 1, c: 3, b: 2 }
// Map from object.
const myMap = new Map(Object.entries(obj))
// Map to Object.
// NOTE: Keys will be cast to strings by `.toString`, so any "complex" key like for example `[1, 2]` will become `1,2`
const newObj = [...myMap.entries()]
.reduce((acc, [key, value]) => (Object.assign(acc, { [key]: value })), {})
const newObjWithObjSpreadSyntax = [...myMap.entries()]
.reduce((acc, [key, value]) => ({...acc, [key]: value }), {})
/* --------- */
// As a fn (breakdown).
/*
* Creates a copy of the `acc` object adding a new property determined by `key` and `value`.
* NOTE: Keys will be cast to strings by `.toString`,
* so any "complex" key like for example `[1, 2]` will become `1,2`
*/
const keyValuePairToObjReducer = (acc, [key, value]) => ({...acc, [key]: value })
/*
* Read as: Given a map => Get it's entries
* -> Spread them into an array of [key, pair]
* -> Reduce the [key, pair] collection calling `keyValuePairToObjReducer`
*/
const mapToObject = (map) => [...map.entries()].reduce(keyValuePairToObjReducer, {})
const myObj = mapToObject(myMap)
@sylvainpolletvillard

This comment has been minimized.

Copy link

commented Oct 3, 2017

small variation : const mapToObject = (map) => Object.assign({},...[...map].map(([k,v])=>({[k]:v})))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.