var map1= new Map();
map1.set("one",1);
var map2 = new Map();
map2.set("two",2);
concatMap = {};
concatMap['one']= map1;
concatMap['two']= map2;
JSON.stringify(concatMap);
//outputs : "{"one":{},"two":{}}"
I also tried:
concatMap = {};
concatMap.one= map1;
concatMap.two= map2;
why am I getting the empty object instead of map 1 and map 2 when I use JSON.stringify()?
Instead of converting my JavaScript object into a JSON string, it returned an empty JSON string. Undefined values. In my case, the issue occurred because my object had properties with undefined values. Take a look at the following example, which will reproduce the issue:
Stringify a JavaScript Object. Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York" }; Use the JavaScript function JSON.stringify () to convert it into a string. var myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
If you return null, null will be added to the JSON string. If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.
In JSON, functions are not allowed as object values. The JSON.stringify () function will remove any functions from a JavaScript object, both the key and the value: This can be omitted if you convert your functions into strings before running the JSON.stringify () function.
This is the expected result. JSON.stringify
does not recognize a Map object as anything different than a regular object, and the JSON spec itself does not have a way to properly store a Map. It just treats the map as a regular object, possibly including any own object properties set on it.
var m = new Map();
// This is not included:
m.set('test', 123);
// This would be included:
m['other'] = 456;
console.log(JSON.stringify(m));
If you are just using string keys, you could use a regular object instead of a Map.
With credit to Tim Brown in his blog post on the subject - when the contents of the Map object are serialisable, you can do:
serialise Map to JSON:
JSON.stringify(Array.from(map.entries()))
de-serialise JSON to Map:
new Map(JSON.parse(jsonStr))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With