When using JSON.stringify on a map object, it returns an empty result

    var map1= new Map();
    map1.set("one",1);
    var map2 = new Map();
    map2.set("two",2);
   concatMap = {};
   concatMap['one']= map1;
   concatMap['two']= map2;
 JSON.stringify(concatMap);

//outputs : "{"one":{},"two":{}}"

I also attempted the following:

concatMap = {};
concatMap.one= map1;
concatMap.two= map2;

Why do I receive empty objects instead of map1 and map2 when using JSON.stringify()?

Answer №1

The desired outcome is as follows: JSON.stringify does not interpret a Map object any differently than a standard object, and the JSON specification itself lacks a mechanism to accurately store a Map. Instead, it treats the map as a regular object and may include any custom object properties set on it.

var m = new Map();

// This will not be included:
m.set('test', 123);

// This will be included:
m['other'] = 456;

console.log(JSON.stringify(m));

If you only use string keys, consider using a plain object rather than a Map.

Answer №2

Simple solution :

In the scenario where you create a Map like this:

const map = new Map();

and populate it with values using:

map.set('key', 'value');

Calling JSON.stringify on the map will result in an empty object being displayed.

To rectify this issue, you can use the following approach:

const objFromMap = Object.fromEntries(map);
JSON.stringify(objFromMap);

Dealing with complex objects :

If your object contains a field that is a map, for instance:

class MyClazz {
   field = new Map();
}
const instance = new MyClazz();
instance.field.set('k', 'v');

When using JSON.stringify, the output will be:

{field: {}}

To resolve this, you need to override the toJSON method as shown below:

class MyClazz {
   field = new Map();
   toJSON(): this {
      return {
          field: Object.fromEntries(this.field),
      }
   }
}
const instance = new MyClazz();
instance.field.set('k', 'v');

After implementing this change, calling JSON.stringify(instance); will give the desired output:

{field: {k: 'v'}}

Answer №3

Credit goes to Tim Brown for sharing a helpful tip in his blog post. He suggests that when the data within a Map object is serializable, you can follow these steps:

  1. Convert Map to JSON:

    JSON.stringify(Array.from(map.entries()))

  2. Convert JSON back to Map:

    new Map(JSON.parse(jsonStr))

Answer №4

It has been pointed out by others that Maps are not currently supported by JSON. However, 2D arrays can be used instead:

const map1 = new Map().set("one", 1),
           map2 = new Map().set("two", 2),
           concatMap = {
              one: [...map1],
              two: [...map2]
           };

const result = JSON.stringify(concatMap);

To decode this information, you can use the following:

 let {one, two} = JSON.parse(result);
 one = new Map(one),
 two = new Map(two);

Answer №5

Utilize the following code snippet to create a new Map:

const newMap = JSON.parse('{}');
newMap[name] = value;

After assigning values, remember to stringify the newMap. The end result will be parsed as a Map<string, string>

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

Angular: Designing personalized hyperlink overlays for text content with a filter

Currently, I am dealing with a json feed that provides information about cars. A portion of the text includes [VIN:'vin_number_is_here']Car make model here[/VIN]. To display this in an ng-repeat loop, I would like to use a filter to process the t ...

What exactly is the functionality of the third parameter (usually next()) behind the scenes in ExpressJS once it is hidden behind the abstraction layer?

Consider this scenario: in the following two code snippets, how is the next() function used as a parameter and how does it facilitate the automatic transition to the next middleware function? What is the underlying mechanism that enables this abstraction? ...

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...

Tips for setting up listeners across multiple modules using socket.io

Last year, I created a multiplayer game using node.js and socket.io. Now, as part of my efforts to enhance the game, I am working on breaking down the code into modules. Currently, I am utilizing expressjs 4.4 along with socket.io 1.0. One challenge I enco ...

Most effective method for structuring a JSON format that contains recurring keys for every item within its array

Currently, I'm creating a JSON object that includes multiple addresses. My main concern is the potential for the JSON size to grow too large, which could impact browser performance and parsing speed in JavaScript. Each address includes keys such as "I ...

Using AJAX to Send Requests to PHP

Embarking on my first ajax project, I believe I am close to resolving an issue but require some guidance. The webpage file below features an input field where users can enter their email address. Upon submission, the ajax doWork() function should trigger t ...

Encountered an error while attempting to load resource: the server returned a 404 (Not Found) status code when trying to load an image in an

I am looking to dynamically load an image when it is selected from a file picker dialog. The code provided below attempts to achieve this, however, the image does not load into the img tag. <script src="https://cdnjs.cloudflare.com/ajax/libs/jq ...

Understanding how to efficiently map through FontAwesome icons using React TypeScript and effectively showcase them on the frontend

I am in the process of developing a versatile component that allows me to input the href, target, and rel attributes, along with specifying the FontAwesome Icon I want to utilize. My goal is to be able to pass multiple icons into this list, which will then ...

Exporting SQLite tables from Android to a JSON file

Having recently started working with JSON, I encountered an issue while trying to export data from two SQLite tables into a JSON text file. Despite successfully fetching the tables and saving them to a file, the results appear invalid when attempting to re ...

What is the best way to retrieve recently inserted data using Sequelize in PostgreSql?

Is there a way to retrieve updated table values after adding a user to the "WOD" table without making an additional query? Currently, when I add a third user to my WOD table, I can only return the first two users because I am unable to access the updated ...

The error message "TypeError: (0, _style.default) is not a function" occurred when using jest along with material

My current configuration looks like this: // .jestrc.json ... "moduleNameMapper": { "style$": "<rootDir>/tests/mock.ts" } // mock.ts export default {} This setup is typically used to exclude assets from jest to pre ...

When the dependency value transitions from 1 to 0, useEffect fails to trigger

I'm really puzzled by how useEffect behaves in this scenario: Check out this code snippet: const numVertices = selectionProvider.verticesSelectionProvider.count; console.log('RENDER ---> COUNT = ', numVertices); useEffect(() => { ...

JavaScript's version of "a certain phrase within a text"

If I'm working in Python and need to verify if a certain value is present in a string, I would use: if "bar" in someString: ... What would be the equivalent code in Javascript for this task? ...

Using JavaScript to submit the value of a checkbox

I'm currently working on a form submission using JavaScript that includes both text input and two checkboxes. <script> function SubmitFormData() { var preferredLocation = $("#preferred_location").val(); var relocation = []; ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Searching for several arrays in Angular

Hello everyone, I have an API that returns data like this: [ [{ "id": 1, "qte": 12, "date_creation": "2020-08-17T00:00:00+02:00", "date_update": "2020-08-17T00:00:00 ...

Utilizing jQuery with variable assignment: A beginner's guide

Struggling to utilize a variable in jQuery? In the script snippet below, I set a variable "divname" with a value, but when using jQuery for fading out, it doesn't work as expected. What I really want is for the description to fade in when hovering ove ...

Include new item in current JSON data using Java

I am facing a challenge in adding a new JSON object to "carTypes" inside the cars.json file. Can anyone guide me on how to achieve this? I can retrieve data from cars.json but do not know the process of adding data to it. The current content of my cars.j ...

Building connections in parse.com using various classes (JavaScript SDK)

Currently using parse.com in conjunction with the JavaScript SDK. Despite my extensive research, I have been unable to find any examples that directly address the issue I am facing. Here is the specific goal I am striving to accomplish: I aim to establi ...

Generating a new array and merging different sets of keys together

Is there a way to modify how items are added to a jQuery array? Here is the current code snippet in use: var sub_updated = []; $('.current-sub-items').each(function() { $(this).find('.prod-select').each(function() { if ($(th ...