How to Convert an Object to a Map in JavaScript
While plain JavaScript objects ({}) are fundamental, the Map object, introduced in ES6, offers several advantages, including the ability to use any data type as a key, a reliable insertion order, and a simple .size property. A common task is to convert an existing plain object into a Map to take advantage of these features.
This guide will explain why you might want to convert an object to a Map and teach you the modern, standard method for doing so using Object.entries().
Why Convert an Object to a Map?
While objects are great, Maps have several key advantages:
- Any Key Type:
Mapkeys can be any value (including functions, objects, or any primitive), whereas object keys must be strings or symbols. - Guaranteed Order: The elements in a
Mapare iterated in insertion order, whereas the order of properties in a plain object is not always guaranteed. - Size Property: A
Maphas a.sizeproperty that directly returns the number of entries, which is more convenient thanObject.keys(obj).length. - Performance:
Maps are highly optimized for frequent additions and removals of key-value pairs.
The Core Method (Recommended): new Map(Object.entries())
The most concise, readable, and idiomatic way to convert an object to a Map is a one-liner that combines Object.entries() and the Map constructor.
The logic:
Object.entries(obj): This method takes an object and returns a two-dimensional array of its[key, value]pairs.new Map(entries): TheMapconstructor accepts an iterable of key-value pairs (like the array fromObject.entries()) and creates a newMapfrom it.
For example, we have a plain object and we want to convert it into a Map.
// Problem: How to convert this object to a Map?
const userObject = {
id: 1,
name: 'Alice',
};
Solution:
const userObject = {
id: 1,
name: 'Alice',
};
// 1. Get the [key, value] pairs
const entries = Object.entries(userObject);
console.log('Entries:', entries); // Output: [ ['id', 1], ['name', 'Alice'] ]
// 2. Create a new Map from the entries
const userMap = new Map(entries);
console.log('Final Map:', userMap); // Output: Map(2) { 'id' => 1, 'name' => 'Alice' }
Output:
Entries: (2) [ ['id', 1], ['name', 'Alice'] ]
Final Map: Map(2) {'id' => 1, 'name' => 'Alice'}
This can be written as a clean one-liner:
const userMap = new Map(Object.entries(userObject));
The Inverse: Converting a Map Back to an Object
To complete the round-trip, you can easily convert a Map back into a plain object using Object.fromEntries().
Solution:
const userMap = new Map([
['id', 1],
['name', 'Alice'],
]);
// This is the direct inverse of Object.entries()
const newUserObject = Object.fromEntries(userMap);
console.log(newUserObject); // Output: { id: 1, name: 'Alice' }
A Note on Older, Verbose Methods
Before Object.entries() was common, this task was solved with more verbose methods, such as a for...in loop or Object.keys().map().
// ⛔️ This is an outdated and verbose way to create a Map.
const myMap = new Map();
for (const key in userObject) {
if (Object.prototype.hasOwnProperty.call(userObject, key)) {
myMap.set(key, userObject[key]);
}
}
While this still works, the new Map(Object.entries(obj)) pattern is faster to write, more declarative, and less error-prone.
Conclusion
Converting a plain object to a Map is a simple task with a clear, modern solution.
- The definitive best practice is to use the
new Map(Object.entries(obj))pattern. - This method is concise, highly readable, and leverages two powerful, built-in JavaScript features designed for this kind of data transformation.
- To convert back, use the inverse operation:
Object.fromEntries(myMap).