[英]How could i turn a Map() into a string as it is, WITHOUT it becoming a json object in js/ts
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.我尝试过
toString()
和模板文字,但显然它们返回 [object Map]。 I also saw that some people converted the Map into an object then called JSON.stringify()
on it.我还看到有些人将 Map 转换为一个对象,然后在其上调用
JSON.stringify()
。
However i don't want my Map be displayed as a JSON Object, but as an actual Map但是我不希望我的地图显示为 JSON 对象,而是显示为实际的地图
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.地图的值是对象,所以我不介意将它们转换为 JSON。
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.
如果你espext其他类型,你可以复杂一点。 Like if you have nested map, make this function recursive.
就像你有嵌套地图一样,让这个函数递归。
if you need to display object like { 'key' => 'value' } and not ":" exists on key or value you can do如果您需要显示像 { 'key' => 'value' } 这样的对象而不是“:”存在于键或值上,您可以这样做
let data = {'key' : 'value'}
JSON.stringify(data).replace(":", " => ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.