Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

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. 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)

{
"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

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

Could someone help, thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get your desired output you could use the Object.entries() function to get the key, value pairs separately. This code segment will turn an object into a list of objects with key value pairs:

test_object = { 
  karachi: "dubai",
  mumbao: "moscow",
};

output = Object.entries(test_object).map(([key, value]) => ({ key, value}));

console.log(output);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...