- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert object to a Map - JavaScript
Suppose we have an object like this −
const obj = { name: "Vikas", age: 45, occupation: "Frontend Developer", address: "Tilak Nagar, New Delhi", experience: 23, };
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
Let's write the code for this −
const obj = { name: "Vikas", age: 45, occupation: "Frontend Developer", address: "Tilak Nagar, New Delhi", experience: 23, salary: "98000" }; 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(6) { 'name' => 'Vikas', 'age' => 45, 'occupation' => 'Frontend Developer', 'address' => 'Tilak Nagar, New Delhi', 'experience' => 23, 'salary' => '98000' }
Advertisements