Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Object to Map conversion in JavaScript
In JavaScript, you can convert an object to a Map using several approaches. Maps offer advantages over objects like guaranteed key insertion order and the ability to use any data type as keys.
Suppose we have an object like this:
const obj = {
name: "Jai",
age: 32,
occupation: "Software Engineer",
address: "Dhindosh, Maharashtra",
salary: "146000"
};
We need to convert this object into a Map while preserving all key-value pairs.
Using Object.entries() (Recommended)
The most concise approach uses Object.entries() with the Map constructor:
const obj = {
name: "Jai",
age: 32,
occupation: "Software Engineer",
address: "Dhindosh, Maharashtra",
salary: "146000"
};
const objectToMap = (obj) => new Map(Object.entries(obj));
console.log(objectToMap(obj));
Map(5) {
'name' => 'Jai',
'age' => 32,
'occupation' => 'Software Engineer',
'address' => 'Dhindosh, Maharashtra',
'salary' => '146000'
}
Using Manual Iteration
For more control, you can iterate through object keys manually:
const obj = {
name: "Jai",
age: 32,
occupation: "Software Engineer"
};
const objectToMap = (obj) => {
const map = new Map();
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
map.set(key, obj[key]);
}
}
return map;
};
console.log(objectToMap(obj));
Map(3) {
'name' => 'Jai',
'age' => 32,
'occupation' => 'Software Engineer'
}
Using Object.keys() with forEach
Another approach using Object.keys() and forEach():
const obj = {
name: "Jai",
age: 32
};
const objectToMap = (obj) => {
const map = new Map();
Object.keys(obj).forEach(key => {
map.set(key, obj[key]);
});
return map;
};
console.log(objectToMap(obj));
console.log(objectToMap(obj).get('name')); // Access specific value
Map(2) { 'name' => 'Jai', 'age' => 32 }
Jai
Comparison
| Method | Code Length | Performance | Readability |
|---|---|---|---|
new Map(Object.entries()) |
Short | Fastest | High |
for...in loop |
Medium | Good | Medium |
Object.keys() + forEach |
Medium | Good | High |
Key Benefits of Maps over Objects
const obj = { name: "Jai", age: 32 };
const map = new Map(Object.entries(obj));
// Size property
console.log("Object size:", Object.keys(obj).length);
console.log("Map size:", map.size);
// Key types
map.set(1, "number key");
map.set(true, "boolean key");
console.log(map);
Object size: 2
Map size: 2
Map(4) {
'name' => 'Jai',
'age' => 32,
1 => 'number key',
true => 'boolean key'
}
Conclusion
Use new Map(Object.entries(obj)) for the most concise object-to-Map conversion. Maps provide better performance for frequent additions/deletions and support any data type as keys.
Advertisements
