Starting a map in typescript

When attempting to initialize the following Map in typescript, I noticed that it appears empty when printed out.

let map: Map<string, object> = new Map<string, object> ([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log(JSON.stringify(map));
// Output shows {}
// However, the initialized values are not displayed

Answer №1

The initialization is correct, but when printed, not all values are displayed as in an array. However, by accessing the keys, you can verify their existence:

let map = new Map([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log(map);
console.log(map.get('api/service/method'));
console.log(map.get('"type": "html"'));

For more information on displaying a JavaScript ES6 map object in the console, you can refer to this link.

As suggested there, you could also spread the map and print it out:

let map = new Map([
    [
        "api/service/method",
        {
            uriPath: {}
        }
    ],
    [
        "\"type\": \"html\"",
        {
            body: {}
        }
    ]
]);

console.log([...map]);

Answer №2

One reason for this behavior is that the JSON.stringify function is unable to stringify a Map, causing it to instead stringify the underlying object and resulting in an empty output.

To address this issue, consider using

console.log(JSON.stringify([...a.entries()]));
as an alternative solution.

Answer №3

When you try to stringify an object, its properties are typically included in the stringification process. However, a Map does not store its data as traditional properties, which can lead to unexpected results if you attempt to stringify it directly.

To properly stringify a Map, consider converting it to an array first:

console.log(JSON.stringify([...map]));

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

Quiz application features various button states for optimal user interaction

I am in the process of creating a quiz that resembles the popular BuzzFeed quizzes such as THIS ONE. Although I have mapped out the logic and have an idea of how to code it to function similarly to the one provided in the link, I am encountering issues wit ...

Ways to exclusively trigger the onclick function of the primary button when dealing with nested buttons in React.js

Let me elaborate on this issue. I have a List component from material-UI, with ListItem set to button=true which makes the entire item act as a button. Within the ListItem, I have added a FontAwesomeIcon. To hide the button, I set its style to visibility: ...

Encountering an issue with sending a direct message on Twitter through OAuth

I am currently developing a JavaScript script to work alongside my C++ application for sending direct messages to users. The script is responsible for constructing the request that I send out. However, whenever I make a request, I keep getting errors like ...

Discover the method for populating Select2 dropdown with AJAX-loaded results

I have a basic select2 box that displays a dropdown menu. Now, I am looking for the most effective method to refresh the dropdown menu every time the select menu is opened by using the results of an AJAX call. The ajax call will yield: <option value=1 ...

Tips for effectively eliminating errors in a redux store

Within my react-redux application, I have implemented a system to catch error responses from redux-saga. These errors are saved in the redux-store and rendered in the component. However, a major challenge arises when trying to remove these errors upon comp ...

Alter the Vue view using an object instead of the url router

Currently working on a chrome extension using Vue.js where I need to dynamically update views based on user interactions. Usually, I would rely on the Vue Router to handle this seamlessly... however, the router is tied to the URL which poses limitations. ...

What steps do I need to follow to develop a checkbox component that mirrors the value of a TextField?

I am working with 3 components - 2 textfields and 1 checkbox Material UI component. My goal is to have the checkbox checked only when there is a value in one of the textfield components. What would be the most effective way to achieve this functionality? ...

What are alternative ways to add an HTML snippet to an existing file without relying on jQuery?

Is it possible to inject the entire content of an HTML file, including all tags, into a specific div using only JavaScript? Alternatively, would it be necessary to append each element individually and create a function for this purpose? ...

Creating a Node.js API using express and mysql to retrieve various data including record count, page number, and implementing pagination functionality

How can I efficiently retrieve and display total_record_count, page_number, page_size, total_pages, has_more information in the response while implementing pagination given that I am limiting my query to 100 results? What would be the most effective approa ...

What could be the reason for reverse geocoding failure following the marker's movement when autocomplete event is triggered in Google Maps?

When I initiate the map and move the pin, the reverse geocoding correctly updates the input with the new address. However, if I manually type in an address using autocomplete and then drag the marker, the reverse geocoding stops functioning: var map; ...

sw-precache-webpack-plugin for webpack's default service worker template

When utilizing the sw-precache-webpack-plugin to create a service worker for my project, I've noticed that while all my fonts, js, and css files are stored in the cache storage, the index/html file is missing. This has resulted in it not functioning p ...

Encountering issues with executing Node.js MySQL query on the second attempt

Currently, I am working on setting up a REST API in Node using Express. The first time I open the URL in the browser, everything works smoothly and I get the expected output. However, upon hitting the API URL for the second time, the application crashes wi ...

Troubleshooting: Unable to load template file content in AngularJS ng-view

Setting up a demo angular app has been quite the challenge for me. Despite my efforts, the content from my partial file (partials/test.html) is not loading into the layout file as expected. Below is a snippet of my index.html: <!DOCTYPE html> <ht ...

The classification of a dictionary and a list in Typescript

Can you spot the difference between the two codes below for defining a type of props? I realized that the first one didn't throw a type error, but I can't figure out why my initial second code was incorrect. To me, it seems like it should work p ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Increase the jQuery level and utilize the .find() method

Currently, I am delving into the realm of jquery and facing a minor hiccup with selectors. Below is the structure of my DOM: <li> <header class="title"> <span>Text</span> <a href="#work-1">My trigger</a> ...

Error: You're attempting to read content that has already been accessed

Encountered the following error message: sp-webpart-workbench-assembly_en-us_b854c4b93cc10a271230fd4a9e7b2b9b.js:661 Uncaught (in promise) TypeError: Already read at t.e.json (sp-webpart-workbench-assembly_en-us_b854c4b93cc10a271230fd4a9e7b2b9b. ...

JavaScript Regular Expression for separating a collection of email addresses into individual parts

I am very close to getting this to work, but not quite there yet. In my JavaScript code, I have a string with a list of email addresses, each formatted differently: var emailList = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data- ...