Basically i want to turn a Map into a string as text. I have tried toString()
and template literals but those return [object Map] obviously. I also saw that some people converted the Map into an object then called JSON.stringify()
on it.
However i don't want my Map be displayed as a JSON Object, but as an actual Map
Suppose i had a Map of
{ 'key' => 'value' }
i want it to be displayed like the above and not like the one below
{
"key": "value"
}
Is there any way i could achieve this?
UPDATE: After some experimenting i finally found a alright-enough method
const convertMapToString = (m: Map<string, IGuildCache | object>) => {
let mapEntries = [...m.keys()]
return '{\n' mapEntries.map(k => {
return ' ' k ' => ' JSON.stringify(m.get(k), null, 2)
}).join(',\n') '\n}'
}
The values of the map were objects so i did not mind converting them into JSON.
CodePudding user response:
You'l have to create your own functions, maybe something like :
function displayMapsWithCustomFormat(m: Map) {
let asStrings = m.map((key, value) => `"${key}" => "${value}"`);
console.log("{\n" asStrings.join(",\n") "}");
}
Not tested, but you can give it a try. You can complexify a bit if you espext other types. Like if you have nested map, make this function recursive.
CodePudding user response:
if you need to display object like { 'key' => 'value' } and not ":" exists on key or value you can do
let data = {'key' : 'value'}
JSON.stringify(data).replace(":", " => ")