0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert Object to Map Easily

Use new Map(Object.entries(yourObject)) to convert an object to a Map in JavaScript.
📋

Examples

Input{"a": 1, "b": 2}
OutputMap { 'a' => 1, 'b' => 2 }
Input{"name": "Alice", "age": 30}
OutputMap { 'name' => 'Alice', 'age' => 30 }
Input{}
OutputMap {}
🧠

How to Think About It

To convert an object to a Map, think of the object as a list of key-value pairs. We can get these pairs using Object.entries(), which returns an array of arrays. Then, we pass this array to the Map constructor to create a Map with the same keys and values.
📐

Algorithm

1
Get the object you want to convert.
2
Use <code>Object.entries()</code> to get an array of key-value pairs from the object.
3
Create a new Map by passing the array of pairs to the Map constructor.
4
Return the new Map.
💻

Code

javascript
const obj = { a: 1, b: 2 };
const map = new Map(Object.entries(obj));
console.log(map);
Output
Map(2) { 'a' => 1, 'b' => 2 }
🔍

Dry Run

Let's trace converting { a: 1, b: 2 } to a Map.

1

Get object entries

Object.entries({ a: 1, b: 2 }) returns [['a', 1], ['b', 2]]

2

Create Map

new Map([['a', 1], ['b', 2]]) creates Map { 'a' => 1, 'b' => 2 }

KeyValue
a1
b2
💡

Why This Works

Step 1: Extract key-value pairs

Using Object.entries() turns the object into an array of [key, value] pairs, which is the format Map expects.

Step 2: Create Map from pairs

Passing the array of pairs to new Map() builds a Map with the same keys and values as the object.

🔄

Alternative Approaches

Manual loop
javascript
const obj = { a: 1, b: 2 };
const map = new Map();
for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    map.set(key, obj[key]);
  }
}
console.log(map);
This method works but is longer and less concise than using Object.entries.
Using Object.keys() and map
javascript
const obj = { a: 1, b: 2 };
const map = new Map(Object.keys(obj).map(key => [key, obj[key]]));
console.log(map);
This creates the pairs manually but is more verbose than Object.entries.

Complexity: O(n) time, O(n) space

Time Complexity

The conversion loops through all object keys once to create entries, so it takes linear time relative to the number of keys.

Space Complexity

Extra space is needed to store the array of entries and the Map, both proportional to the number of keys.

Which Approach is Fastest?

Using Object.entries() with new Map() is concise and efficient compared to manual loops.

ApproachTimeSpaceBest For
Object.entries + MapO(n)O(n)Simple and fast conversion
Manual loopO(n)O(n)More control, but verbose
Object.keys + mapO(n)O(n)When you want to transform keys or values
💡
Use Object.entries() with new Map() for a quick and clean conversion.
⚠️
Trying to pass the object directly to new Map() without converting it to entries causes errors.