How to Convert an Object to a Map in JavaScript

Let’s look at some ways to quickly convert an object to a Map in JavaScript.

1. Object.entries() in Map() Constructor

To convert an object to a Map, we can call the Object.entries() method with the object as an argument, and pass the result to the Map() constructor to create the Map object. For example:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const map = new Map(Object.entries(obj));

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);

Note: Object.entries() transforms an object into an array of key-value pairs that the Map() constructor uses to create the Map elements.

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const entries = Object.entries(obj);

// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(entries);

We can generate the array without using Object.entries(), like this:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const entries = Object.keys(obj).map((key) => [
  key,
  obj[key],
]);

// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(entries);

2. Iterate over Object Keys and Add Elements to Map

We can also convert an object to a Map by iterating through the object keys, using the Map set() method to add an element to the resulting Map for each key. We can obtain the keys with the Object.keys() method and loop through them with the forEach() method. For example:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const map = new Map();
Object.keys(obj).forEach((key) => {
  map.set(key, obj[key]);
});

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);


Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *