Skip to content

Instantly share code, notes, and snippets.

@alvaropinot
Created October 3, 2017 17:58
Show Gist options
  • Save alvaropinot/f6a5011b55f51a07a3f12c53e890e2aa to your computer and use it in GitHub Desktop.
Save alvaropinot/f6a5011b55f51a07a3f12c53e890e2aa to your computer and use it in GitHub Desktop.
"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
Copy link

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