Create json string from js Map and String

You can use Array.prototype.reduce along with spread notation to tersely convert your map to the format you need.

var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");
var myString = "string value";

function mapToObj (map) {
  return [...map].reduce((acc, val) => {
    acc[val[0]] = val[1];
    return acc;
  }, {});
}

const json = JSON.stringify({
  myMap: mapToObj(myMap),
  myString: myString
});

console.log(json);

JSON stringification has the special behavior for objects, arrays and functions.

For example:

JSON.stringify( function(){} ); // output: undefind
JSON.stringify( [2,undefined,function(){}, 5] ); //output: "[2,null,null,5]"

One way for solving that is to define a toJSON() method for it that returns a JSON-safe version of the object.

var myJson = {};
myJson.toJson = function() {
    return {  /* what ever you need*/}
}

Second, and more simple, using ES6 syntax:

JSON.stringify([...myMap]);

Using ES6 syntax, and especially if you have nested maps (otherwise Idan Dagan's answer is simpler), you can use the JSON.stringify()'s second argument, the reducer, as follows:

JSON.stringify(myMap, (key, value) => (value instanceof Map ? [...value] : value));


You can write a short conversion function to make a map into an object that can be stringified.

console.clear()

function mapToObj(map){
  const obj = {}
  for (let [k,v] of map)
    obj[k] = v
  return obj
}

const myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");

const myString = "string value"

const myJson = {};
myJson.myMap = mapToObj(myMap);
myJson.myString = myString;
const json = JSON.stringify(myJson);

console.log(json)

Here is a version that that presumably would work where Map exists but some other ES6 constructs do not (though, this seems like an editor settings issue).

console.clear()

function mapToObj(map){
  var obj = {}
  map.forEach(function(v, k){
    obj[k] = v
  })
  return obj
}

var myMap = new Map();
myMap.set("key1", "value1");
myMap.set("key2", "value2");
myMap.set("key3", "value3");

var myString = "string value"

var myJson = {};
myJson.myMap = mapToObj(myMap);
myJson.myString = myString;
var json = JSON.stringify(myJson);

console.log(json)