JavaScript Map — Create From Object

The ECMAScript 2015 specification introduced a Map class. A Map instance provides convenient methods around key-value-pairs. Objects in JavaScript are key-value-pairs as well. Yet, you can’t pass an existing object to the map constructor.

This tutorial shows you how to create a JavaScript map from an existing object.

Node.js Series Overview

Create A JavaScript Map From an Object

The map constructor in JavaScript expects an array of key-value-tuples, like [ ['name', 'Marcus'], ['future', 'Studio'] ]. This format seems a bit off because you may expected to pass the plain object to the map’s constructor.

The good thing: you can create the expected structure using JavaScript’s Object.entries method:

const users = {  
  'marcus': { id: 1, name: 'Marcus' },
  'norman': { id: 2, name: 'Norman' },
  'christian': { id: 3, name: 'Christian' }
}

const map = new Map(  
    Object.entries(users)
)

map.size  
// 3

map.has('marcus')  
// true

This-Binding Won’t Work in Functions

JavaScript objects can have functions as their values. When creating a map from an object containing functions, you’ll loose the this binding:

const user = {  
  firstname: 'Future',
  lastname: 'Studio',
  fullname() {
    return `${this.firstname} ${this.lastname}`
  }
}

user.fullname()  
// 'Future Studio'

/**
 * Creating a map from an object containing functions may
 * create binding issues related to the `this` keyword.
 */
const futureStudio = new Map(  
    Object.entries(user)
)

map.size  
// 3

map.has('fullname')  
// true

const fullname = map.get('fullname')  
fullname()  
// 'undefined undefined'

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 exports an extended and improved Map class. Use this supercharged Map class to create map instances. The constructor accepts the array of key-value-pairs and also plain JavaScript objects:

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

const users = {  
  'marcus': { id: 1, name: 'Marcus' },
  'norman': { id: 2, name: 'Norman' },
  'christian': { id: 3, name: 'Christian' }
}

const map = new Map(users)

map.has('marcus')  
// true

Sweet!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.