17

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 
}
Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59
  • What is the question ? – Weedoze May 10 '17 at 11:03
  • *"...converted to normal json type structure..."* JSON is a *textual notation* for data exchange. [(More.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. Do you mean a plain object? `{}`? – T.J. Crowder May 10 '17 at 11:04

4 Answers4

21

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);
Emad Salah
  • 815
  • 1
  • 8
  • 19
13

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

The Map's keys must be strings or Symbols, or things that can be meaningfully converted to strings, since property keys in objects can only be strings or Symbols.


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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • This is just exactly what I was looking for. Thanks! – jwehrle Mar 07 '20 at 05:21
  • @jwehrle - :-) Things have moved on since the original answer above; I've updated it to show `Object.fromEntries`, which was added in ES2019. – T.J. Crowder Mar 07 '20 at 09:00
  • For some reason I have not been able to figure out Object.fromEntries is throwing a type error in this situation. So I went with a more basic method. – jwehrle Mar 07 '20 at 18:28
  • @jwehrle - Huh. Well, whatever works. :-) But if you want to know why, post a question with your code and point me at it. (Or of course, someone else may get there first). Happy coding! – T.J. Crowder Mar 07 '20 at 19:16
4

One-liner to convert Map to plain Object:

Object.assign({}, ...[...m.entries()].map(([k, v]) => ({[k]: v})))
Pang
  • 9,564
  • 146
  • 81
  • 122
2

Better way to convert map to object

let jsonResponse = {};
            for(let [key,val] of MapObject.entries()){
                jsonResponse[key]= val;
            }

console.log(jsonResponse);
Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59