Search code examples
arraysjsontypescriptstringify

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.


Solution

  • 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);

    You can adapt this code to select the desired parts of your object and format them as you like. There are other Object functions you can see in the documentation.