Skip to content
Advertisement

Search for multiples Keys on new Map()

Normally what we do is like

const hash = new Map()

hash.set(key,value)

And when we want to retrieve the information just

hash.get(specificKey)

One of the benefits that Map has is that we can put whatever we want as key or value.

I’m trying to set a multiple value of keys on the “key” part of the map, that’s not the problem is later when I want to get the information

Example:

[
    {name:"Pedro",email:"test1@gmail.com"},
    {name:"Anibal",email:"test2@gmail.com"},
]

I want to create the key of the map with both properties of the object (name, email), and the value is ALL the iterated register so…

const hash = new Map()
for (register of registers) {
    const { name, email } = register
    hash.set([name, email], register)
}  

The problem is when I want to GET the register by one of the properties on the key.

We know that the key could be [“Pedro”,”test1@gmail.com]

How I can get the value of the Map if the key I want to get could be just “Pedro” or just “test1@gmail.com”

It is possible? 🙁 Thank you

___________________- Answer to @Kevin Kinney

Thank you for answering. The idea that I want to do is to avoid this;

enter image description here

I dont want to have a find inside the map. Any different approach?

Advertisement

Answer

One idea, if you know only a few of the properties would be used as keys

const hash = new Map()
for (register of registers) {
    const { name, email } = register
    hash.set(name, register)
    hash.set(email, register)
}

This will allow fast access to the value in the map, but increases the memory usage.

Otherwise I don’t think a hashmap is the right idea if you don’t know what key you will be expecting to use.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement