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

The Javascript arr.reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left to right) and the return value of the function is stored in an accumulator. 

Example:

Javascript




function convertObjectToMap(obj) {
    const map = Object.keys(obj).reduce((result, key) => {
        result.set(key, obj[key]);
        return result;
    }, new Map());
  
    return map;
}
  
// Example plain object
let obj = {
    prop_1: 'val_1',
    prop_2: 'val_2',
    prop_3: 'val_3'
};
const mapFromObject = convertObjectToMap(obj);
  
// Accessing Map values
console.log(mapFromObject.get("prop_1"));
console.log(mapFromObject.get("prop_2"));
console.log(mapFromObject.get("prop_3"));


Output

val_1
val_2
val_3

We have a complete list of Javascript ES6 features, to check those please go through this Introduction to ES6 article.



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...