Simple solution :
In the scenario where you create a Map like this:
const map = new Map();
and populate it with values using:
map.set('key', 'value');
Calling JSON.stringify on the map will result in an empty object being displayed.
To rectify this issue, you can use the following approach:
const objFromMap = Object.fromEntries(map);
JSON.stringify(objFromMap);
Dealing with complex objects :
If your object contains a field that is a map, for instance:
class MyClazz {
field = new Map();
}
const instance = new MyClazz();
instance.field.set('k', 'v');
When using JSON.stringify, the output will be:
{field: {}}
To resolve this, you need to override the toJSON method as shown below:
class MyClazz {
field = new Map();
toJSON(): this {
return {
field: Object.fromEntries(this.field),
}
}
}
const instance = new MyClazz();
instance.field.set('k', 'v');
After implementing this change, calling JSON.stringify(instance); will give the desired output:
{field: {k: 'v'}}