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
- Create an object.
- Create a new map.
- Pass the object to the map and set its properties.
Example: In this example, we will convert an object into a map using the object.entries method.
Javascript
let obj = {
prop_1: 'val_1' ,
prop_2: 'val_2' ,
prop_3: 'val_3'
};
function GFG_Fun() {
const map = new Map(Object.entries(obj));
console.log(
"Val of prop_2 is " + map.get( 'prop_2' ));
}
GFG_Fun()
|
Output
Val of prop_2 is val_2
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
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;
}
let obj = {
prop_1: 'val_1' ,
prop_2: 'val_2' ,
prop_3: 'val_3'
};
const mapFromObject = convertObjectToMap(obj);
console.log(mapFromObject.get( "prop_1" ));
console.log(mapFromObject.get( "prop_2" ));
console.log(mapFromObject.get( "prop_3" ));
|
We have a complete list of Javascript ES6 features, to check those please go through this Introduction to ES6 article.
Last Updated :
11 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...