Javascript how to retrieve value from a Map that has an EnumValue as key
Asked Answered
H

2

6

I'm querying a database in Javascript where I get back a Map object. The problem is that the key of some entry in the map is an object, an EnumValue to be precise.

I can't seem to find a way to directly retrieve this kind of entries. The only that comes to my mind is to iterate on every single key of the map and check if it's an object.

So, if I console.log the output I get from the query, it looks like this:

Map {
    EnumValue { typeName: 'T', elementName: 'label' } => 'user',
    'gender' => [ 'f' ],
    'identityid' => [ '2349fd9f' ],
    'name' => [ 'Erika' ],
    'email' => [ '[email protected]' ],
    EnumValue { typeName: 'T', elementName: 'id' } => 4136,
    'lastname' => [ 'Delgato' ] 
}

I've naively already tried to get the entry using something like this:

const enumId = { typeName: 'T', elementName: 'label' };
map.get(enumId)

But of course it returns undefined.

Any ideas?

Haste answered 16/6, 2019 at 17:24 Comment(0)
H
4

So, for saving the time to anyone else that incours in this problem I'll write the solution here.

This problem is specific to values retrieval in a Janusgraph database, using the gremlin javascript client (version 3.4.2 used here).

When appending valueMap(true) to a traversal, the result is the one in the question I posted. Going through the gremlin library, I found out that inside the object t from gremlin.process.t this EnumValues can be found:

id
key
label
value

Then using the id or label it is possible to directly retrieve the values with those nasty keys.

An example:

// Let's say we already have the Map from the question stored in a map variable
// To get the id of the result you can do the following
const t = gremlin.process.t;
const id = map.get(t.id);
console.log(id) // 4136
Haste answered 17/6, 2019 at 19:21 Comment(0)
S
0

Map in javascript work by reference. It does not make a deep comparison, only check if the pointer is the same. This will not work:

var x = new Map()
x.set({},'lala')
x.get({}) // undefined

But this will work:

var x = new Map()
var player = {name: 'ben'}
x.set(player, 50)
x.get(player) // 50
Svelte answered 16/6, 2019 at 17:39 Comment(2)
Thanks! That's what I was afraid of sadly. So basically since I have no reference of the objects used as keys, I'm forced to iterate all the keys.Haste
@Haste If the object content doesn't change you can use JSON.stringify when setting and getting it.Svelte

© 2022 - 2024 — McMap. All rights reserved.