EN
JavaScript - convert Map to object
6 points
In this article, we would like to show you how to convert Map to object in JavaScript.
In this example, we use Object.fromEntries()
method to convert Map
to object.
xxxxxxxxxx
1
const map = new Map([
2
['key1', '1'],
3
['key2', 2],
4
]);
5
6
const object = Object.fromEntries(map);
7
8
console.log(JSON.stringify(object)); // { key1: '1', key2: 2 }
Note:
Object.fromEntries()
method was introduced in ECMAScript 2019 (ES10).
In this section, we present solution for older versions of JavaScript. The solution below uses forEach()
to iterate over Map
and save key/value pairs inside the result object
.
xxxxxxxxxx
1
function toObject(map) {
2
var object = {};
3
map.forEach(function(value, key) {
4
object[key] = value;
5
});
6
return object;
7
}
8
9
10
// Usage example:
11
12
var map = new Map([
13
['key1', '1'],
14
['key2', 2],
15
]);
16
17
var object = toObject(map);
18
19
console.log(JSON.stringify(object)); // { key1: '1', key2: 2 }