Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access an item in map by two-item array key

I create a simple map:

const myMap = new Map([[[3,6], 'hello']]);

Where the key is a two-item array.
If I try to access it like so:

console.log(myMap.get([3,6]))

I will get undefined. However if I get the keys of that map:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const keyArray = [...myMap.keys()];
console.log(myMap.get(keyArray[0])) // hello

I will be able to access that key. This is even though keyArray[0] is just an array of [3,6].
Is it related to something in its prototype? What makes it different than just trying to access the map with a new array of [3,6]? And then what would be a practical way to access such key easily and hopefully dynamically?

>Solution :

because every time you use [3,6] it create new array that has a different reference from the previous one so no [3, 6] are a like you can check that by logging this statement:

console.log([3,6] === [3,6]) // this log false always 

to solve your issue you can save the array inside another variable to save the reference then use this variable to access the value inside your Map.

you can try this in you code

const myArray = [3,6]
const myMap = new Map([[myArray, 'hello']]);
console.log(myMap.get(myArray)) // this output 'hello'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading