close

How to convert a plain object into an ES6 Map?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to convert a plain object into an ES6 Map? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to convert a plain object into an ES6 Map ?

  1. How to convert a plain object into an ES6 Map ?

    to convert a plain object into an ES6 Map ES6
    convert object to map:
    const objToMap = (o) => new Map(Object.entries(o));
    convert map to object:
    const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )

  2. How to convert a plain object into an ES6 Map ?

    to convert a plain object into an ES6 Map ES6
    convert object to map:
    const objToMap = (o) => new Map(Object.entries(o));
    convert map to object:
    const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )

Method 1

Do I really have to first convert it into an array of arrays of key-value pairs?

No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:

function* entries(obj) {
    for (let key in obj)
        yield [key, obj[key]];
}

const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'

Method 2

ES6

convert object to map:

const objToMap = (o) => new Map(Object.entries(o));

convert map to object:

const mapToObj = (m) => [...m].reduce( (o,v)=>{ o[v[0]] = v[1]; return o; },{} )

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment