How to get Map as an object in javascript ES6?

Kunal Vashist picture Kunal Vashist · May 10, 2017 · Viewed 10.7k times · Source

My Class is using es6 to create an map object at node level, using Map()--"set" function.When class is called i want the map object to get converted to normal json type structure. I am using moongoose to retreive the data from database.

res.json(MapObject);

After using this res.json whole content inside parent node is getting empty.

{success:{},
 error:{},
redirectMe:false}

Have Map Object like this

{
  success: 
   Map {
     'String1' => 'true',
     'Object1' => [ [Object],
                    [Object],
                    [Object],
                    [Object],
                    [Object]
                  ]
     'String2' => 100 
     }
  error: Map {},
  redirectMe: false 
}

I want to get result as an Object but when I tries to get it not able to get anything

Wanted something like

{
  success: 
    {
     'String1' : 'true',
     'Object1' : [ [Object],
                    [Object],
                    [Object],
                    [Object],
                    [Object]
                  ]
     'String2' : 100 
     }
  error: {},
  redirectMe: false 
}

Answer

Emad Salah picture Emad Salah · Apr 3, 2019

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);