Javascript

How to Convert a Map to an Object in JavaScript

In this article, we’ll be looking at some ways to easily convert a Map to an object in JavaScript. 1. Object.fromEntries() To convert a...

Written by Luci · 53 sec read >

In this article, we’ll be looking at some ways to easily convert a Map to an object in JavaScript.

1. Object.fromEntries()

To convert a Map to an object, we can use the Object.fromEntries() method, passing the Map as an argument. For example:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);
const obj = Object.fromEntries(map);
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

NoteObject.fromEntries() can transform any list of key-value pairs into an object. For example, it can directly transform the array of key-value pairs that we passed to the Map() constructor:

const arr = [
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
];
const obj = Object.fromEntries(arr);
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

2. Iterate over Map and Create Keys in Object

Another way to convert a Map to an object is iterate over the entries of the Map and create a new key on the object for each of them. For each entry, we set the key name and value to the entry name and value respectively. For example:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);
const obj = {};
map.forEach((value, key) => {
  obj[key] = value;
});
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

Note: We can also iterate over the Map with the for...of loop:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);
const obj = {};
for (const [key, value] of map) {
  obj[key] = value;
}
// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);
Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x