Created
November 12, 2018 20:16
-
-
Save blakeyoder/22a60464d919360f30e3c51cb2337462 to your computer and use it in GitHub Desktop.
Map to JSON
This file contains hidden or 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
mapToJson = (inputMap) => { | |
if (!(inputMap instanceof Map)) { | |
throw new Error(`${inputMap} is not a valid Map`); | |
} | |
const outputObj = {} | |
inputMap.forEach((k, v) => { | |
return outputObj[v] = k; | |
}); | |
return outputObj; | |
} | |
const input = [[1, ['hello', 'world']], ['fnc', () => {console.log('fnc called')}]]; | |
const inputMap = new Map(input); | |
const toJson = mapToJson(inputMap); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple script that converts an ES6
Map
to a valid object representation.Map
offers some advantages over object. For example,Map
is a built-in iterable and provides a more intuitive interface for iterating over elements that do objects. However, objects are easier to consume (I haven't heard of aMap
represented API yet ;)).