简体   繁体   English

将带有字典的 typescript class object 转换为 Z0ECD11C1D7A287401D148A23BBD7A2F8 数组

[英]Converting a typescript class object with dictionary to a JSON array

After some digging I decided my backend needed to consume duplicate keys and as a consequence my frontend can no longer send a dictionary as a JSON string.经过一番挖掘,我决定我的后端需要使用重复的键,因此我的前端不能再将字典作为 JSON 字符串发送。 See my previous question .请参阅我之前的问题

After applying the solution provided应用提供的解决方案后

let mediatagRequest = new MediaTagRequest(tags);
const headers = { 'content-type': 'application/json' }

let jsonObject = {};
for (let entry of mediatagRequest.tags.entries())
{
  jsonObject[entry[0]] = entry[1];
}

const body = JSON.stringify({
  tags: jsonObject
});

My current output (which is what I then wanted)我目前的 output (这是我当时想要的)

{
"tags": {
    "city": "Karachi"
}

However my needs have changed and after a bit of of struggle I couldn't get my desired output to be like this但是我的需求发生了变化,经过一番挣扎后,我无法让我想要的 output 变成这样

{
    "tags": [
        {
            "key": "city",
            "value": "Karachi"
        },
        {
            "key": "city",
            "value": "Mumbai"
        }
    ]
}

Could someone help, thank you.有人可以帮忙吗,谢谢。

To get your desired output you could use the Object.entries() function to get the key, value pairs separately.要获得所需的 output,您可以使用Object.entries() function 分别获取键、值对。 This code segment will turn an object into a list of objects with key value pairs:此代码段会将 object 转换为具有键值对的对象列表:

 test_object = { karachi: "dubai", mumbao: "moscow", }; output = Object.entries(test_object).map(([key, value]) => ({ key, value})); console.log(output);

You can adapt this code to select the desired parts of your object and format them as you like.您可以将此代码调整为 select object 的所需部分,并根据需要对其进行格式化。 There are other Object functions you can see in the documentation.您可以在文档中看到其他Object功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM