I am currently unsure of how to retrieve the value of a particular key within a JavaScript map that contains multiple sets of data

I am working with a JavaScript map that contains multiple values. Here is an example (simplified for clarity):

Map(2) { 
  'group1' => {
    username: 'userTest',
    dsId: '710300636817653790',
    openDate: '2021-12-13 18:29:16'
 },
  'group2' => {
    username: 'Juojo',
    dsId: '477581625841156106',
    openDate: '2021-12-13 18:29:23'
 }
}

My goal is to retrieve the username value ('Juojo') from the second group of data. I attempted to do this:

console.log(map.get(group2.username));

However, this returns "undefined". When I try without the ".username" (console.log(map.get(group2));), it gives me:

{
  username: 'Juojo',
  dsId: '477581625841156106',
  openDate: '2021-12-13 18:29:23'
}

I only want the output to be "Juojo"

Answer №1

Retrieve the username attribute from the object fetched using the fetch method.

console.log(map.fetch(group2).username);

If there is a possibility that the key may not be present, you have the option to utilize the optional chaining operator, which will result in undefined instead of throwing an error.

console.log(map.fetch(group2)?.username);

Answer №2

To access the object stored in your map, you can retrieve it and then read its properties as shown in the example below:

const myMap = new Map([ 
  ['group1',{
    username: 'userTest',
    dsId: '710300636817653790',
    openDate: '2021-12-13 18:29:16'
 }],
  ['group2', {
    username: 'Juojo',
    dsId: '477581625841156106',
    openDate: '2021-12-13 18:29:23'
 }]
])

const userName = myMap.get('group2').username;

console.log(userName);

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

Prevent the bottom row from being sorted

I have implemented sortable table rows in my angular project, however the sorting functionality also affects some query-ui code elements. Now I am looking to exclude the last row from being sortable. HTML <div ng:controller="controller"> <ta ...

I am looking to showcase a series of icons linked together by connecting lines

I have successfully designed the layout and added icons, but I am facing difficulty in creating connecting lines between them. I attempted to utilize CSS borders and pseudo-elements, yet I cannot achieve the desired outcome. If anyone could offer a CSS-ba ...

What's the correct way to utilize "for loops" in Jquery without making errors?

Having an issue: I am working with a basic unordered list of truncated posts. Each post should expand when clicked using the .replaceWith method. However, I am facing a problem where clicking on any post returns the content of all posts in the list instead ...

Updating objects in Angular 8 while excluding the current index: a guide

this.DynamicData = { "items": [ { "item": "example", "description": "example" }, { "item": "aa", "description": "bb" }, ...

Display the accurate duration based on the dates selected in an HTML form automatically

If someone has office hours on Monday, Wednesday, and Friday from 7:00 am to 7:00 pm, and on Tuesday and Thursday from 10:00 am to 9:00 pm, the dropdown menu should display only the timings of 7:00 AM to 7:00 PM if the selected date is a Monday, Wednesda ...

Contrast between using "export { something }" and "export something" in JavaScript modules

Can you explain the difference between the following code snippets: import something from "../something"; export { something }; vs import something from "../something"; export something; I noticed in the react-is package from react, there is an export ...

When calling a method that has been created within a loop, it will always execute the last method of the

In my project, I am utilizing node version 0.8.8 in conjunction with express version 3.0. Within the codebase, there exists an object named checks, which contains various methods. Additionally, there is an empty object called middleware that needs to be p ...

The map loop is failing to display anything, despite the presence of data

My React component is making a call to a PHP endpoint that returns an array of folders in a directory for an internal forms file browser. The API call is successful, and the response is correct. However, when I try to map over the array, nothing is being r ...

Creating JSON from identical user interface components

I have created a form similar to this one: https://jsfiddle.net/6vocc2yn/ that generates a JSON output like below: { "List": [ { "Id": 10, "Name": "SDB_SOLOCHALLENGE_CHALLENGE_DESC_10", "email": "<a href="/cdn-cgi/l/email-pr ...

What measures can be taken to stop AngularJS binding from occurring repeatedly?

Currently, I am facing an issue with my select element: <select ng-model="p.value" ng-options="q for q in p.value"> <option value="">Select an animation</option> </select> The initial values in p.value are ['AAAAA', &apo ...

Unable to use the res.send() function

I've been working on a Node.js project. Within the validate.js file, I have defined a class Validate with a static method validateTicket and exported the class at the end. validate.js file const request = require("request"); const config = { urlBas ...

Issues with Jquery Checkboxes Functionality

Hi everyone, yesterday I had a question and since then I have made quite a few changes to my code. Right now, I am attempting to make some JavaScript work when a specific checkbox is checked. However, nothing is happening when I check the checkbox. Can any ...

Build an immersive experience by incorporating threejs into A-Frame to develop a spherical environment filled with 360-degree videos

I've been working on a VR project that involves 360° videos in VR. My concept was to construct a sphere and apply a 360° video as the material. I've already managed to create my own Sphere Component and map a 360° image onto it! Similar to t ...

Using AJAX to submit a form and then refreshing the page within the current tab

I am facing an issue with my web page that contains multiple tabs, some of which have forms. Whenever a form is successfully submitted, the page reloads but always goes back to the default first tab. To address this, I am attempting to use a storage variab ...

Node.js - CSRF Protection Token Undefined

I've been facing challenges with setting up CSRF token generation, and I seem to be missing something. server.js: // configuration ====================================================================== var express = require('express'); va ...

What could be causing my component to not update after I modify the states?

When I make an ajax request and update the state with the response data, my list of items does not rerender as expected. Even though the state is updated successfully, the changes are not reflected in the UI. export class Tiles extends React.Component { ...

Creating a custom comparison method between two select dropdowns using the jQuery Validation plugin

In my HTML code, I have two select elements: <label for="h_slat_type">Horizontal Slat Type</label> <select name="h_slat_type" id="h_slat_type"> <option disabled="disabled" selected>Select</option> ...

Using localStorage in Next.js, Redux, and TypeScript may lead to errors as it is not defined

Currently, I am encountering an issue in my project where I am receiving a ReferenceError: localStorage is not defined. The technologies I am using for this project are Nextjs, Redux, and Typescript. https://i.stack.imgur.com/6l3vs.png I have declared ...

Angular 2: Changing HTTP Requests

I am trying to include a single parameter in all my web requests to disable caching forcibly. My goal is to append ?v=1535DC9D930 // Current timestamp in hex to the end of each request. I am coding this in plain ES5 JS, but the documentation is in Types ...

Issue with Sheetjs: Date format is not recognized when adding JSON data to a

I am struggling to export JSON data to Excel while maintaining the correct date format of 2020-07-30 07:31:45. Despite trying suggestions from a helpful post on sheetjs, I still couldn't get it right. Here is an example of the JSON data: { "so ...