HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How can I convert a Map to a JavaScript object and vice versa?

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
mapjavascriptobjectandhowcanversaconvertvice

Problem

Oftentimes, when working with Map objects, we need to convert from or to plain JavaScript objects. This can be useful when you need to use the Map's key-value pairs as an object or vice versa.
Using Map.prototype.entries(), we can convert a Map to an array of key-value pairs. Then, we can use Object.fromEntries() to convert the array to an object.
Similarly, using Object.entries(), we can convert an object to an array of key-value pairs. Then, we can use the Map() constructor to convert the array to a Map.

Solution

const mapToObject = map => Object.fromEntries(map.entries());

mapToObject(new Map([['a', 1], ['b', 2]])); // {a: 1, b: 2}


Similarly, using Object.entries(), we can convert an object to an array of key-value pairs. Then, we can use the Map() constructor to convert the array to a Map.

Code Snippets

const mapToObject = map => Object.fromEntries(map.entries());

mapToObject(new Map([['a', 1], ['b', 2]])); // {a: 1, b: 2}
const objectToMap = obj => new Map(Object.entries(obj));

objectToMap({a: 1, b: 2}); // Map {'a' => 1, 'b' => 2}

Context

From 30-seconds-of-code: convert-map-to-object

Revisions (0)

No revisions yet.