Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelWalker-git/d1dcbe9d7637d9beaaa564ca15f568e3 to your computer and use it in GitHub Desktop.
Save MichaelWalker-git/d1dcbe9d7637d9beaaa564ca15f568e3 to your computer and use it in GitHub Desktop.
Convert ES6 Map to Object Literal
let map = new Map();
map.set("a", 1);
map.set("b", 2);
map.set("c", 3);
let obj = Array.from(map).reduce((obj, [key, value]) => (
Object.assign(obj, { [key]: value }) // Be careful! Maps can have non-String keys; object literals can't.
), {});
console.log(obj); // => { a: 1, b: 2, c: 3 }
@MichaelWalker-git
Copy link
Author

Instead of converting the map -> array -> iterating over array / filling in new object

Could you do this?

const convertMapsToObjects = (mapInstance) => {
  const obj = {};
  for(let prop of map){
    obj[prop[0]] = prop[1];
  }
 return obj;
}

http://jsben.ch/mGhq1

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