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
Selected Reading
Object to Map conversion in JavaScript
Suppose, we have an object like this −
const obj = {
name: "Jai",
age: 32,
occupation: "Software Engineer",
address: "Dhindosh, Maharasthra",
salary: "146000"
};
We are required to write a JavaScript function that takes in such an object with key value pairs and converts it into a Map.
Example
The code for this will be −
const obj = {
name: "Jai",
age: 32,
occupation: "Software Engineer",
address: "Dhindosh, Maharasthra",
salary: "146000"
};
const objectToMap = obj => {
const keys = Object.keys(obj);
const map = new Map();
for(let i = 0; i < keys.length; i++){
//inserting new key value pair inside map
map.set(keys[i], obj[keys[i]]);
};
return map;
};
console.log(objectToMap(obj));
Output
The output in the console −
Map(5) {
'name' => 'Jai',
'age' => 32,
'occupation' => 'Software Engineer',
'address' => 'Dhindosh, Maharasthra',
'salary' => '146000'
} Advertisements
