[英]Converting a typescript class object with dictionary to a JSON string
I'm looking for a way to convert my typescript class with dictionary to a JSON object without the brackets.我正在寻找一种将带字典的 typescript class 转换为不带括号的 JSON ZA8CFDE6331BD49EB2AC96F891 的方法。
this is my class这是我的 class
export class MediaTagRequest {
tags: Map<string, string>;
constructor(tags: Map<string, string>) {
this.tags = tags;
}
}
My instantiation我的实例化
let tags = new Map<string, string>();
tags.set("city", "Karachi");
let mediatagRequest = new MediaTagRequest(tags);
const headers = { 'content-type': 'application/json'}
const body = JSON.stringify(Object.keys(mediatagRequest.tags.entries()));
My current output:我目前的 output:
[["city","Karachi"]]
My desired output:我想要的 output:
{
"tags": {
"city": "Karachi"
}
}
Can someone help me please, thank you.有人可以帮我吗,谢谢。
You can convert a map to an object directly by using Map#entries
and Object.fromEntries
.您可以使用
Map#entries
和 Object.fromEntries 直接将 map 转换为Object.fromEntries
。
Here is an example:这是一个例子:
const m = new Map(); m.set("foo", "hello"); m.set("bar", "world"); const obj = Object.fromEntries(m.entries()); console.log(obj);
You can further leverage the replacer parameter of JSON.stringify
to directly do this when converting an entire object:您可以进一步利用JSON.stringify 的 replacer
JSON.stringify
在转换整个 object 时直接执行此操作:
function mapReplacer(key: string | number | Symbol, value: any) {
if (value instanceof Map) {
return Object.fromEntries(value.entries());
}
return value;
}
class MediaTagRequest {
tags: Map<string, string>;
constructor(tags: Map<string, string>) {
this.tags = tags;
}
}
let tags = new Map<string, string>();
tags.set("city", "Karachi");
let mediatagRequest = new MediaTagRequest(tags);
console.log(JSON.stringify(mediatagRequest, mapReplacer))
JavaScript demo: JavaScript 演示:
function mapReplacer(key, value) { if (value instanceof Map) { return Object.fromEntries(value.entries()); } return value; } class MediaTagRequest { constructor(tags) { this.tags = tags; } } let tags = new Map(); tags.set("city", "Karachi"); let mediatagRequest = new MediaTagRequest(tags); console.log(JSON.stringify(mediatagRequest, mapReplacer))
You can use any of this to create object
and then create response body using it您可以使用其中任何一个来创建
object
,然后使用它创建响应正文
Option 1选项1
let jsonObject = {};
tags.forEach((value, key) => {
jsonObject[key] = value;
});
Option 2选项 2
let jsonObject = {};
for (let entry of tags.entries()) {
jsonObject[entry[0]] = entry[1];
}
Option 3选项 3
let jsonObject = {};
for (let key of tags.keys()) {
jsonObject[key] = value;
}
creating response body创建响应体
const body = JSON.stringify({
tags: jsonObject
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.