Skip to content

Instantly share code, notes, and snippets.

@blakeyoder
Created November 12, 2018 20:16
Show Gist options
  • Save blakeyoder/22a60464d919360f30e3c51cb2337462 to your computer and use it in GitHub Desktop.
Save blakeyoder/22a60464d919360f30e3c51cb2337462 to your computer and use it in GitHub Desktop.
Map to JSON
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);
@blakeyoder
Copy link
Author

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 a Map represented API yet ;)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment