1

I'm looking for a way to convert my typescript class with dictionary to a JSON object without the brackets.

this is my 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:

[["city","Karachi"]]

My desired output:

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

Can someone help me please, thank you.

2 Answers 2

3

You can convert a map to an object directly by using Map#entries and 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:

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

Playground Link

JavaScript demo:

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can use any of this to create object and then create response body using it

Option 1

let jsonObject = {};
tags.forEach((value, key) => {  
    jsonObject[key] = value;
});

Option 2

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

Option 3

let jsonObject = {};
for (let key of tags.keys()) {  
    jsonObject[key] = value;          
}

creating response body

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

1 Comment

ah yes I already added the last line that you added to your solution. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.