Transforming a TypeScript class instance containing a dictionary into a JSON formatted string

I am seeking a solution to convert my typescript class with a dictionary into a JSON object format without the brackets.

Here is my class:

export class MediaTagRequest {
    tags: Map<string, string>; 
    constructor(tags: Map<string, string>) {
      this.tags = tags;
    }
}

This is how I instantiate it:

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

Current output:

[["city","Karachi"]]

Desired output:

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

If anyone could assist me with this issue, I would greatly appreciate it. Thank you.

Answer №1

To directly convert a map to an object, you can use Map#entries in combination with Object.fromEntries.

Here's a sample code snippet:

const m = new Map();

m.set("foo", "hello");
m.set("bar", "world");

const obj = Object.fromEntries(m.entries());

console.log(obj);

If you want to convert the entire object including maps, you can utilize the replacer parameter in JSON.stringify:

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

Check out the JavaScript demonstration below:

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

Answer №2

You have the flexibility to choose any of these methods to construct an object and then formulate a response body based on it

Method 1

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

Method 2

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

Method 3

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

Formulating response body

const response = JSON.stringify({
    tags: obj
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting Recursive Logic Problem with hasOwnProperty in JavaScript and JSON

JSON data with a specific problem highlighted by the comment // doesn't get parsed currently: var oarsObject = [{ "coordinateReferenceSystem": "26782,15851 <-- not in a value", "positionReferenceType": "geogWgs84", "geogWgs84": ...

Guide on correctly setting up and utilizing refs for a themed functional component in TypeScript and React Native

Primary Objective: I aim to have two text inputs where pressing return on the first one will shift the focus to the next input. Let's begin with the configuration (using TypeScript). I have a customized text input with specific color settings, and I ...

Exploring the Use of Overloads and Callbacks in TypeScript

Currently, I am exploring the implementation of the builder pattern and trying to create functions that support optional parameters as arguments. Here is an example of how I am approaching this: new Service().OnAction(Actions.Add, () => { alert(1); }) ...

Having trouble establishing a connection with the C# Controller when processing the frontend request

Having trouble implementing the Search by siteId functionality using typescript and C#. The issue arises when trying to connect to the C# controller from the frontend request. The parameter I need to pass is siteId. Below is the code snippet: HTML: ...

Enhance the efficiency of parsing JSON data

I am looking to extract and analyze the JSON data provided by this API (taken from their sample page): I have created a parsing method that takes quite some time (several seconds on my Galaxy A5) to process the extensive data: This is the approach I have ...

What is the process for manually triggering an observable error?

I'm currently developing an Angular application where I am making a REST call using HTTP. Here is the code snippet: login(email, password) { let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-url ...

Karma's connection was lost due to a lack of communication within 10000 milliseconds

The Karma test suite is encountering issues with the following message: Disconnected, because no message in 10000 ms. The tests are not running properly. "@angular/core": "7.1.3", "jasmine-core": "3.3.0", "karma-jasmine": "1.1.2", The failure seems t ...

How to eliminate top-level elements in a JSON object

Here is the initial JSON payload: { "Products": { "Product": [ { "ProductID": 458761, "Designation": "CB 024-2001", "EntryDate": "2002-01-20T19:00:00.000-05:00", "S1": "024", "S2": 20 ...

Creating a validation error in Angular: When a user submits an empty form, radio buttons will be highlighted in red

I have encountered an issue already posted on GitHub regarding this matter, but unfortunately, no solution has been provided yet. You can view the issue here: https://github.com/angular/components/issues/11333 I was wondering if there are any workarounds ...

Volley unable to connect to the server when attempting to retrieve JSON data in an

When creating the application for local network quizzes, I encountered a hurdle with an Android JSON issue. The code was failing to connect and retrieve a JSONArray from my server. In quiz.java, the JsonObjectRequest function wasn't executing properl ...

A guide on displaying JSON in a Twig template in Symfony2

I am facing a challenge on how to pass JSON data to Twig for rendering a template. I attempted to pass the JSON using the JsonResponse object, but I couldn't figure out how to render the template. TarifasController.php <?php /* * This file is p ...

Building Unique Password Validation with Angular 5

I'm attempting to implement custom password validation for a password field. The password must be a minimum of 8 characters and satisfy at least two of the following criteria but not necessarily all four: Contains numbers Contains lowercase letters ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

Alert: Using Angularfire SDK could result in console log issues

I've been encountering this persistent warning that I just can't seem to get rid of no matter what I try. Here are the versions I'm using: angular 11.0.1 @angular/fire 6.1.3 firebase 7.0.0 || 8.0.0 https://i.sstatic.net/5Tyt5.png ...

What is the best way to showcase information from a JSON file using AngularJS?

I have a JSON that looks like the following: { "count": 67, "0": { "id": "2443", "name": "Art Gallery", "category": { "id": "2246", "name": "Gifts & Memories" }, "deckLocation": [ { "id": "2443", ...

Error: Missing key 'client'

How do I extract the customer's email address from this JSON data? Is there a way to retrieve the customer's email in this JSON using a Python loop without encountering a KeyError? { "orders":[ { "created_at":"2020-06-11T07:56 ...

Tips on how to iterate through a JSON object and store its values in an array

I am attempting to extract values from an external JSON file and store certain values in an array. Here is my code : $.getJSON("https://link.to.my.json", function(data) { console.log(data); // this will display the information in the console }); I am ...

Visualizing connections between elements using SVG from JSON data files

As a newcomer to D3, I am facing challenges in visualizing my json file. My task involves plotting the locations (sites) as circles with their radius determined by the "amount" value. The concept of working with nodes and links is causing me great confusio ...

Retrieve the inventory of assets linked to a Solana wallet address

Currently, I am utilizing the web3 SDK for Solana to inquire about account balances or conduct transactions. My inquiry now is regarding the feasibility of executing one of the following operations: Retrieve a list of assets associated with a specified ...

Tips on storing JSON array data in mongoose via req.body?

I've been struggling with this issue for some time now. After successfully using JSON and req.body to save data to my MongoDB database in Postman, I decided to work with arrays for the first time. However, I'm encountering difficulties. (Just t ...