How to convert a plain object into ES6 Map using JavaScript ?
The task is to convert a JavaScript Object into plain ES6 Map using JavaScript. we’re going to discuss few techniques.
Approach
- Create an object.
- Create a new map.
- Pass the object to the map and set its properties.
Example 1:
<!DOCTYPE HTML> < html > < head > < title > How to convert a plain object into ES6 Map using JavaScript ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ p > < script > var up = document.getElementById('GFG_UP'); up.innerHTML = "Click on the button to "+ "convert the JavaScript Object into map."; var down = document.getElementById('GFG_DOWN'); var obj = { prop_1: 'val_1', prop_2: 'val_2', prop_3: 'val_3' }; var heading = document.getElementById('h1'); function GFG_Fun() { const map = new Map(Object.entries(obj)); down.innerHTML = "Val of prop_2 is " + map.get('prop_2'); } </ script > </ body > </ html > |
chevron_right
filter_none
Output:
-
Before clicking on the button:
-
After clicking on the button:
Example 2:
<!DOCTYPE HTML> < html > < head > < title > How to convert a plain object into ES6 Map using JavaScript ? </ title > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksForGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;" > </ p > < script > var up = document.getElementById('GFG_UP'); up.innerHTML = "Click on the button to "+ "convert the JavaScript Object into map."; var down = document.getElementById('GFG_DOWN'); var obj = { prop_1: 'val_1', prop_2: 'val_2', prop_3: 'val_3' }; function createMap(obj) { let map = new Map(); Object.keys(obj).forEach(key => { map.set(key, obj[key]); }); return map; } function GFG_Fun() { const map = createMap(obj); down.innerHTML = "Val of prop_1 is " + map.get('prop_1'); } </ script > </ body > </ html > |
chevron_right
filter_none
Output:
-
Before clicking on the button:
-
After clicking on the button: