Access an item in map by two-item array key

Advertisements

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:

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'

Leave a ReplyCancel reply