Home > Mobile >  Search for multiples Keys on new Map()
Search for multiples Keys on new Map()

Time:08-13

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:"[email protected]"},
    {name:"Anibal",email:"[email protected]"},
]

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","[email protected]]

How I can get the value of the Map if the key I want to get could be just "Pedro" or just "[email protected]"

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?

CodePudding user response:

No, this is not possible

You want access in a non-standard way so what you can do is create two mappings for each value. One goes from pedro and one goes from [email protected]

Then when you need to retrieve the value you can get it by either

CodePudding user response:

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.

  • Related