How to get Map as an object in javascript ES6?
You can convert a map to an object easily using a native JS function:
Object.fromEntries(map);
Note: This function is part of the ECMAScript 10 spec and is supported by Node.js 12+ and Chrome 73+, could also be polyfilled to work on older platforms using this plugin
const map = new Map();
// Setting up some sample data
map.set("foo", "bar");
map.set("pets", ["Fido", "Foobar", "Al"]);
// Convert map to object
const convertedMap = Object.fromEntries(map);
console.log(convertedMap);
One-liner to convert Map to plain Object:
Object.assign({}, ...[...m.entries()].map(([k, v]) => ({[k]: v})))
Now that JavaScript has Object.fromEntries
(added in ES2019, easily polyfilled), this is a one-liner:
const obj = Object.fromEntries(map);
Live Example:
const map = new Map();
map.set("string1", true);
map.set("someArray", [{a:1}, {b:2}, {c:3}]);
map.set("string2", 100);
const obj = Object.fromEntries(map);
console.log(obj);
.as-console-wrapper {
max-height: 100% !important;
}
Previous answer: If you have a Map
and you want to convert it to a plain object, that's easily done if the Map
's keys are strings or Symbols or something (numbers, for instance) that can meaningfully be converted to strings.
You just loop over its keys:
const obj = {};
for (const key of map.keys()) {
obj[key] = map.get(key);
}
Live Example:
const map = new Map();
map.set("string1", true);
map.set("someArray", [{a:1}, {b:2}, {c:3}]);
map.set("string2", 100);
const obj = {};
for (const key of map.keys()) {
obj[key] = map.get(key);
}
console.log(obj);
.as-console-wrapper {
max-height: 100% !important;
}
That said, as Kunal noted, it might make more sense to use entries
(and you don't need .entries()
, you can just use of map
to get the default iterator, which is for entries).