Back to results for “JSON”
JavaScript › Map, Set, WeakMap & WeakSet

How do you convert between a Map and a plain object?

Intermediate

Answer

Object.fromEntries(map) converts a Map's entries into a plain object; conversely, new Map(Object.entries(obj)) builds a Map from a plain object's own enumerable properties.
const map = new Map([['a', 1], ['b', 2]]);
const obj = Object.fromEntries(map); // { a: 1, b: 2 }
const backToMap = new Map(Object.entries(obj));
Real-world example Converting a Map used internally for fast lookups into a plain object before sending it as JSON.

Common follow-ups: Does JSON.stringify() work directly on a Map, or does it need this conversion first?