Convert Map to JSON object in Javascript
I hope this function is self-explanatory enough. This is what I used to do the job.
/*
* Turn the map<String, Object> to an Object so it can be converted to JSON
*/
function mapToObj(inputMap) {
let obj = {};
inputMap.forEach(function(value, key){
obj[key] = value
});
return obj;
}
JSON.stringify(returnedObject)
Given in MDN, fromEntries()
is available since Node v12:
const map1 = new Map([
['foo', 'bar'],
['baz', 42]
]);
const obj = Object.fromEntries(map1);
// { foo: 'bar', baz: 42 }
For converting object back to map:
const map2 = new Map(Object.entries(obj));
// Map(2) { 'foo' => 'bar', 'baz' => 42 }