How to Convert an Object to a Map in JavaScript

Last updated on June 01, 2022
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);
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also