Steps for converting an object of the Map type to a string

class sample{
    title : string
    items : Map<string,string> =new Map()
    constructor(){
        this.title='Sunny'
        this.items.set('fruit','Apple')
    }
}
var s = new sample()
console.log(s)
console.log(JSON.stringify(s))

This is the output:

sample { items: Map { 'fruit' => 'Apple' }, title: 'Sunny' }
{"items":{},"title":"Sunny"}

Is there a way to display the data in JSON like this:

{"items":{'fruit':'Apple'},"title":"Sunny"}

or

{"items":['fruit':'Apple'],"title":"Sunny"}

Alternatively, is there a simpler method to represent key-value relationships in JSON and TypeScript?

Answer №1

Intro: Let's follow the convention of starting class names with an uppercase letter, therefore changing test to Test below.

As Map cannot be stringified by default, there are three options available:

  1. Add a toJSON method to your Test class and return an object with modified children (likely an array of arrays), or

  2. Create a subclass of Map that includes toJSON and utilize it in Test

  3. Develop a replacer for use with JSON.stringify that handles instances of Map.

While option #1 is functional, it would require updates to the toJSON method whenever properties are added or removed from Test, potentially leading to maintenance challenges:

class Test {
  name: string
  children: Map<string, string> = new Map()
  constructor() {
    this.name = 'KIANA'
    this.children.set('name', 'OTTO')
  }
  toJSON() {
    return {
      name: this.name,
      children: [...this.children.entries()]
    }
  }
}
var t = new Test()
console.log(JSON.stringify(t))

Here's a demonstration:

class Test {
  name/*: string*/
  children/*: Map<string, string>*/ = new Map()
  constructor() {
    this.name = 'KIANA'
    this.children.set('name', 'OTTO')
  }
  toJSON() {
    return {
      name: this.name,
      children: [...this.children.entries()]
    }
  }
}
var t = new Test()
console.log(JSON.stringify(t))

[...this.children.entries()] generates an array of [name, value] pairs for the map.

Personally, I prefer option #2, a JSON-compatible Map:

class JSONAbleMap extends Map {
  toJSON() {
    return [...this.entries()]
  }
}

...which you can then apply in Test:

class Test {
  name: string
  children: Map<string, string> = new JSONAbleMap()
  constructor() {
    this.name = 'KIANA'
    this.children.set('name', 'OTTO')
  }
}
var t = new Test()
console.log(JSON.stringify(t))

Example of usage:

class JSONAbleMap extends Map {
  toJSON() {
    return [...this.entries()]
  }
}

class Test {
  name/*: string*/
  children/*: Map<string, string>*/ = new JSONAbleMap()
  constructor() {
    this.name = 'KIANA'
    this.children.set('name', 'OTTO')
  }
}
var t = new Test()
console.log(JSON.stringify(t))

Alternatively, opt for choice #3, a replacer function applied with JSON.stringify:

function mapAwareReplacer(key: string|Symbol, value: any): any {
    if (value instanceof Map && typeof value.toJSON !== "function") {
        return [...value.entries()]
    }
    return value
}

...and incorporate it when using JSON.stringify:

console.log(JSON.stringify(t, mapAwareReplacer))

Live demo:

function mapAwareReplacer(key, value) {
    if (value instanceof Map && typeof value.toJSON !== "function") {
        return [...value.entries()]
    }
    return value
}

class Test {
  name/*: string*/
  children/*: Map<string, string>*/ = new Map()
  constructor() {
    this.name = 'KIANA'
    this.children.set('name', 'OTTO')
  }
}
var t = new Test()
console.log(JSON.stringify(t, mapAwareReplacer))

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

What is the best way to implement my custom toolbar button to utilize the form's validation function within react-admin?

I have developed a unique Toolbar with a custom button that is supposed to mimic the behavior of the standard SaveButton but also perform additional actions after the form is submitted. The form should only be able to submit if it passes validation, and an ...

I encountered an issue with Angular where it is throwing an error stating that the property 'catch' does not exist on the type 'Observable<Object>'

I have been working on an angular application that interacts with a python flask API. During development, I encountered the need to display results passed from the backend. To achieve this, I created an angular service. Below is the code for the angular s ...

Eliminate values from an array by utilizing either a for loop or a custom filtering function

I need help with removing specific URLs from an array every time they appear. Here is the list of URLs I want to filter out: "https://basueUrl.com/Claim" "https://basueUrl.com/ExplanationOfBenefit" This is my current array: Array= [ "https://b ...

Display larger images dynamically by hovering over thumbnails using PHP

Is there a way to display an image when I hover over a thumbnail using PHP, similar to the functionality on this website? I'm looking for a solution to implement this feature. ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Unable to successfully remove item using Asyncstorage

const deleteProduct = prod => { Alert.alert( 'Delete Product', `Are you sure you want to remove ${prod.id}?`, [ { text: 'Cancel', style: 'cancel', }, { ...

Utilize the GitHub API response in a React.js application with TypeScript for seamless integration

When I make a request to the GitHub API using axios, I encounter an issue. Here is the URL I am trying to fetch data from: api.github.com/users/fariasmateuss/repos After fetching the data, I attempt to map it as follows: interface RepositoryProps { fu ...

Tips for adding a text input field within a dropdown menu

Could someone provide guidance on how to place an input text box within a dropdown without using bootstrap? I came across this image showing what I am looking for: https://i.stack.imgur.com/f7Vl9.png I prefer to achieve this using only HTML, CSS, and Jav ...

Is there a way to decrease these values in my firestore using a loop?

My goal was to decrease the quantities of the color upon form submission. The setup includes forms where users can select a product, enter quantity, choose colors, and add more products. Upon submitting the data, it looks like this: https://i.sstatic.net ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

Error 400 encountered when attempting to log in with React through Google on mobile devices

Currently, I am implementing the React Google Login package to handle user authentication on my website. Surprisingly, it functions perfectly on desktops; however, when tested on mobile devices, an annoying Error 400: redirect_uri_mismatch pops up. Despi ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...

Avoid having gulp's uglify plugin remove es6 code

I've encountered an issue while using gulp babel to compile es6. It seems that uglify is stripping out my es6 code completely. Strangely, I'm not receiving any errors in my command line during the process. Have you faced this problem before? Any ...

How to Pause or Temporarily Halt in Jquery?

Looking to lift the object up, wait 1000ms, and then hide it. I found this snippet of code: $("#test").animate({"top":"-=80px"},1500) .animate({"top":"-=0px"},1000) .animate({"opacity":"0"},500); However, using ".animate({"to ...

Performing an AJAX request to the database when a change occurs, prior to submitting the

In my user setup/create form, I am including a field for the users' license/certification number which needs to be validated and returned to a specific DIV Onchange before the form is submitted. I have heard that using AJAX POST is the way to achieve ...

Ways to evaluate and contrast two JSON values in JavaScript by their key names?

I am dealing with two JSON arrays that look like this: array1=[{a:1,b:2,c:3,d:4}] & array2=[{a:2,b:5,c:3,d:4}] Is there a way to determine which key in array2 has the same value as one of the keys in array1? For example, in array 1, key b has a value ...

What is the process of creating an asynchronous function that will resolve a promise when the readline on('close') event is triggered within it in Typescript?

Here's a code snippet I'm working with: private readFile() { var innerPackageMap = new Map<string, DescriptorModel>(); // Start reading file. let rl = readline.createInterface({ input: fs.createReadStream(MY_INPUT_FILE ...

When attempting to evaluate JSON data on a specific computer, the function JSON

Something strange is happening and I can't seem to figure it out, causing a big issue for me. I am currently working on a .Net web application that utilizes JSON (not json2) along with other JS libraries. In one specific proxy, the function JSON.eval ...

What is the best way to extract all Enum Flags based on a Number in TypeScript?

Given: Enum: {1, 4, 16} Flags: 20 When: I provide the Flags value to a function Then: The output will be an array of flags corresponding to the given Enum: [4, 16] Note: I attempted to manually convert the Enum to an array and treat values as numb ...

Seeking assistance with setting up checkboxes to sort through elements in an array

As a beginner in the world of HTML, JavaScript, and CSS, I have a basic understanding of these languages. My current class project requires me to create checkboxes that can filter out content from an array based on the presence of a certain letter in the a ...