I dont know how to get a value of a specific key on a Javascript map (with multiple groups of data)

Viewed 278

i have a JavaScript map with multiple values it is like this (i simplified the code for obvious reasons):

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'
 }
}

I want to get the username value (Juojo) of the second group of data. I tried doing this:

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

but this logs me "undefined", when i try without the ".username" (console.log(map.get(group2));) it replys me:

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

I only want the reply to be "Juojo"

2 Answers

Access the username property on the object returned by get.

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

If it is possible for the key to not exist, you can use the optional chaining operator, which will produce undefined in that case instead of causing an error.

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

You should try to get the object which has stored in your map then try to read the property of returned object, like below example:

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);

Related