JavaScript Map — Transform to an Object

A previous tutorial showed you how to create a JavaScript Map instance from an existing object. This time we’re doing it the other way around: transforming a JavaScript map into a plain object.

Node.js Series Overview

Create a JavaScript Object From a Map

Modern JavaScript engines ship with the Object.fromEntries() method. Creating an object from entries is what you’re looking for when creating a plain object from a map instance.

Here’s an example transforming a map of users to an object:

const map = new Map()  
map.set('marcus', { name: 'Marcus' })  
map.set('norman', { name: 'Norman' })  
map.set('christian', { name: 'Christian' })

const usersObject = Object.fromEntries(map)  

Use the @supercharge/map Package

I’m the maintainer of the @supercharge/map package providing a better Map class for JavaScript.

The @supercharge/map package provides a .toObject() method allowing you to transform the map instance to a plain JavaScript object:

const Map = require('@supercharge/map')

const users = new Map()  
    .set('marcus', { name: 'Marcus' })
    .set('norman', { name: 'Norman' })
    .set('christian', { name: 'Christian' })

const obj = users.toObject()  
// {
//   'marcus': { name: 'Marcus' }
//   'norman': { name: 'Norman' }
//   'christian': { name: 'Christian' }
// }


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.