flaviut
flaviut

Reputation: 2143

How do I convert a Javascript Map to Object?

I need to pass a Map to some code that expects an object. How do I go from

new Map([["a", 1], ["b", 2]])

to

{a: 1, b: 2}

?

Upvotes: 3

Views: 1647

Answers (5)

f-CJ
f-CJ

Reputation: 4481

Object.fromEntries() has been included in ECMAScript 2019 so it will be implemented in all major browsers soon.

At the time of writing (April 11, 2019), Chrome 73 and Firefox 63 have already implemented the feature, also BabelJs 7.4

const myMap = new Map([["a", 1], ["b", 2]]);
const myObj = Object.fromEntries(myMap);
console.log(myObj);

Upvotes: 5

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

You can use Map.prototype.forEach like this:

let map = new Map([["a", 1], ["b", 2]]),
    res = {};

map.forEach((value, key) => res[key] = value);

console.log(res);

Upvotes: 3

Denys Séguret
Denys Séguret

Reputation: 382140

You don't need to chain map to array conversions and many function calls, you can use a straightforward loop:

var obj = {};
for (var [key, value] of m) obj[key] = value;

Be careful that keys will be converted to strings in that process if they aren't already.

Upvotes: 5

Nina Scholz
Nina Scholz

Reputation: 386578

You could use Object.assign and map the items as new objects.

var map = new Map([["a", 1], ["b", 2]]),
    object = Object.assign({}, ...[...map].map(([k, v]) => ({ [k]: v })));


console.log(object);

Upvotes: 2

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can turn that Map to array using spread syntax and then add to object.

var map = new Map([["a", 1], ["b", 2]])

var obj = {}
var arr = [...map]
arr.forEach(e => obj[e[0]] = e[1]);

console.log(obj)

Upvotes: 1

Related Questions