Created
October 3, 2017 17:58
-
-
Save alvaropinot/f6a5011b55f51a07a3f12c53e890e2aa to your computer and use it in GitHub Desktop.
"FUNctional" π Map πΊ to object π
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
small variation :
const mapToObject = (map) => Object.assign({},...[...map].map(([k,v])=>({[k]:v})))