Skip to content

Instantly share code, notes, and snippets.

@lukehorvat
Last active January 8, 2024 10:32
Show Gist options
  • Save lukehorvat/133e2293ba6ae96a35ba to your computer and use it in GitHub Desktop.
Save lukehorvat/133e2293ba6ae96a35ba 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 }
@vjpr
Copy link

vjpr commented Sep 9, 2021

If a value in the map can be an array of maps you need:

const toObject = (map = new Map) => {
  if (!(map instanceof Map)) return map
  return Object.fromEntries(Array.from(map.entries(), ([k, v]) => {
    if (v instanceof Array) {
      return [k, v.map(toObject)]
    } else if (v instanceof Map) {
      return [k, toObject(v)]
    } else {
      return [k, v]
    }
  }))
}

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