How to useMap() and forEach() Method in Javascript

In this method, we will convert an object into a map by passing it to another function called createMap() and using the object.forEach() method

Example:

Javascript




let 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);
    console.log(
        "Val of prop_1 is " + map.get('prop_1'));
}
GFG_Fun()


Output

Val of prop_1 is val_1

How to convert a plain object into ES6 Map using JavaScript ?

The task is to convert a JavaScript Object into a plain ES6 Map using JavaScript. we’re going to discuss a few techniques. To understand the difference between a map and an object please go through the Map vs Object in JavaScript article.

Below are the following approaches to converting a plain object into ES6 Map using JavaScript:

  • Using map() Constructor and Object Entries Method
  • Using Map() and forEach() Method
  • Using Map() and reduce() Method

Similar Reads

Approach 1: Using map() Constructor and Object Entries Method

Create an object. Create a new map. Pass the object to the map and set its properties....

Approach 2: Using Map() and forEach() Method

...

Approach 3: Using Map() and reduce() Method

In this method, we will convert an object into a map by passing it to another function called createMap() and using the object.forEach() method...