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);


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

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