EN
JavaScript - convert object to Map
6 points
In this article, we would like to show you how to convert object to Map in JavaScript.
In this section, we present solution using Object.entries()
.
xxxxxxxxxx
1
const object = {
2
'key1': '1',
3
'key2': '2'
4
};
5
6
const map = new Map(Object.entries(object));
7
8
console.log(map.get('key1')); // 1
9
console.log(map.get('key2')); // 2
Note:
Object.entries()
was introduced in ECMAScript 2017 (ES8).
In the example below, we get object keys using keys()
method, then we iterate over the keys
and add entries to a Map
object using set()
method.
xxxxxxxxxx
1
function toMap(object) {
2
var map = new Map();
3
var keys = Object.keys(object);
4
for (var i = 0; i < keys.length; ++i) {
5
var key = keys[i];
6
map.set(key, object[key]);
7
}
8
return map;
9
}
10
11
12
// Usage example:
13
14
var object = {
15
'key1': '1',
16
'key2': '2'
17
};
18
19
var map = toMap(object);
20
21
console.log(map.get('key1')); // 1
22
console.log(map.get('key2')); // 2