What is the best way to retrieve a {collection object} from a JavaScript map?

My application utilizes a third-party library that returns the map in the following format:

public sids: Map<SocketId, Set<Room>> = new Map();

When I try to access it using the code below:

io.of("/").adapter.sids.forEach(function(value, key) {
    console.log(key + ' = ' + value)
})

The output appears as follows:

qZq18yG3TkoBPXNTAAAC = [object Set] 
84q_yQYKB7JjOPAIAAAD = [object Set]

Upon logging the entire map, I see this structure:

Map(2) {
  'qZq18yG3TkoBPXNTAAAC' => Set(2) { 'qZq18yG3TkoBPXNTAAAC', 'demo' },
  '84q_yQYKB7JjOPAIAAAD' => Set(2) { '84q_yQYKB7JjOPAIAAAD', 'demo' }
}

Now, my query lies in how to access the values within the [object Set]. I attempted to use JSON.stringify but it didn't yield any results.

After implementing the recommended code snippet like so:

  io.of("/").adapter.sids.forEach((set,key)=> {
        let demo = [...set]
        console.log('Key:', key,' Set to array: ', [...set] , set);
    });

I encountered unexpected results:

Key: UJ3HwAIsHTgE9qvrAAAB Set to array: [] Set(2) { 'UJ3HwAIsHTgE9qvrAAAB', 'demo' } Key: Kvlt-mtnrE5NxMykAAAD Set to array: [] Set(2) { 'Kvlt-mtnrE5NxMykAAAD', 'demo' }

Answer №1

If you need to transform a Set into an array, you can easily do so

const map = new Map([
  ['abc123', new Set(['abc123','example'])],
  ['def456', new Set(['def456','example'])]
])

map.forEach((set, key) => {
  console.log('Key:', key,' Array representation of the set: ', [...set]);
  console.log('Set contains "example" =', set.has('example'))
});

Answer №2

Consider the element definition Set<Room>. The map currently holds an object of type Set<Room>. This becomes clear in

io.of("/").adapter.sids.forEach(function(value, key) {
    console.log(key + ' = ' + value)
})

In this code snippet, value represents a Set<Room>, which is why you cannot append to ' = '.

You can iterate through the Set and access individual Room objects (each with their unique properties).

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

Inject Custom ASP Control Script into the DOM dynamically upon registration

During a postback, I am loading my ascx control when a dropdown change event occurs. Parent C#: private void ddlChange() { MyControl myCtr = (CallScript)Page.LoadControl("~/Controls/MyControl.ascx"); myCtr.property = "something"; // setting publ ...

Utilizing PHP for a server-side backup in case the CDN is inaccessible

Looking to simulate some server-side functionality: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> if (typeof jQuery == 'undefined&apo ...

Node.js application encountering crashes while attempting to download a sizable file

I'm currently working on a project that involves converting HTTP URLs to torrents. The program is designed for downloading smaller files, typically between 1-500Mb. However, I've encountered an issue where the application crashes or times out whe ...

ways to assign the total of string array elements to the $scope variable

I've been working on binding the total sum of selected checkboxes within a table. I'm almost there, but something isn't quite right. The image above shows 2 checkboxes selected. https://i.sstatic.net/70af2.jpg The code snippet below showcas ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...

Script tags that are included within the element Vue vm is bound to can result in a template error

Here is the Laravel layout template that I am currently working with: <html lang="en"> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="{{ URL::asset('css/libs.css') }}" rel="stylesheet"> ...

Is it possible to implement a modal within my API services?

Hello, I am in need of assistance. I am looking to display a modal every time my API returns an error. Can someone please help me figure out how to achieve this? I am currently using React hooks. const restService = (path, responseType = 'json') ...

Creating an animated time-based scrollable bar chart in javascript

As someone who is new to JavaScript and charting, I am seeking assistance with a specific task. Despite browsing various JavaScript charting libraries and examples, none seem to address my issue: My goal is to generate dynamic stacked bar charts, as depic ...

Framer Motion causes a crash in a Next.js application with the error message: "Unable to find named export 'useId'"

I am encountering an error in my Next.js app that I can't seem to trace back to its source. Strangely, the code triggering the error is not something I wrote myself. error - file:///Users/cheq/Desktop/cheqo/node_modules/framer-motion/dist/es/component ...

Dealing with Challenges in Constructing JQuery URLs

I'm facing an issue with loading a website into a specific div (div.content). The website I'm trying to load requires a login through a POST request. When the javascript attempts to load the site, it recognizes the redirection to the login form ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

Utilize flexbox to create a list that is displayed in a column-reverse layout

I am facing a challenge in displaying the latest chat person in the 1st position (active) using Firebase. Unfortunately, Firebase does not have a date field which makes it difficult to achieve this. I have attempted converting the date into milliseconds an ...

Angular app sends a JSON request and receives no data in response

It seems like Angular may be loading the page before fully receiving all the information from JSONP. There are times when refreshing the page multiple times eventually displays the information, but it's not consistent. Interestingly, the code used on ...

What techniques can be used to optimize the SEO of HTML generated by JavaScript? How does React.js go about achieving this

Is my webpage optimized for SEO if it was created using appendChild and innerHTML with JavaScript? Can react.js improve the SEO of a webpage? ...

What exactly is the purpose of measuring "First Load JS" in the @next/bundle-analyzer tool?

The analysis generated by the NextJS bundle analyzer appears as follows: Page Size First Load JS ┌ λ / 12 ...

How can the node version be set globally in NVM?

While utilizing Node Version Manager, setting the node version to the latest one in the current directory can be done using nvm use node. But how can you specify a specific version to use? ...

Hidden IFrame for Jquery File Upload

I was looking for a quick guide on setting up an AJAX-style file upload using a hidden iframe. Below is the section of HTML code related to the form: <div id = "file" class = "info"> <form id="file_upload_form" method="post" enctype=" ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

Adjust the internal state within a Vue3 component using a window function

Creating a "Loader" component that is fully independent and functional just by being included in the layout requires exposing some methods for use. Here is the code I have come up with: <script setup> let active = false; function show() { active ...