joh pik
joh pik

Reputation: 11

Call Array key of Map object

Does anyone knows how to directly call a array key of a Map Object.

As shown in below code, I can map.get(arr), but not map.get([0, 1, 2, 3])

const map = new Map()
const arr = [0,1,2,3]
map.set(arr, "I am some number")

map.get(arr) // "I am some number"
map.get([0,1,2,3]) // undefined

Upvotes: 1

Views: 85

Answers (4)

Amadan
Amadan

Reputation: 198324

You can't. Map compares objects by object identity. [0, 1, 2, 3] !== [0, 1, 2, 3] as they are different objects, even if they hold the same data.

The nearest thing you can do is to try to convert the array to something you can compare meaningfully:

const map = new Map()
const arr = [0,1,2,3]
map.set(JSON.stringify([0, 1, 2, 3]), "I am some number")

console.log(map.get(JSON.stringify([0, 1, 2, 3])))

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074335

That's correct, you have to use the same array (as in map.get(arr)), not just an equivalent array. Key comparison is like === (except that NaN matches itself). So just like this shows false:

console.log([0, 1, 2, 3] === [0, 1, 2, 3]); // false

...using map.get([0, 1, 2, 3]) is guaranteed not to find anything, because there isn't any entry in the map keyed by that array.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386604

You need the same object reference for getting the value from a Map.

If you like to use a starting part of the array as key, you need to get all keys from the map and check against with the new array.

var map = new Map,
    key0 = [0, 1, 2, 3],
    key1 = [0, 1, 2, 3];

map.set(key0, "I am some number");
console.log(map.get(key0)); // "I am some number"

for (let key of map.keys())
    if (key.join('|') === key1.join('|'))
        console.log(map.get(key));

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370759

Separate arrays aren't === to each other - your arr does not refer to the same array container as the [0,1,2,3] that you pass to map.get. To do something like this, you'd have to iterate over the map's keys and find the one whose values all match:

const map = new Map()
const arr = [0,1,2,3];
map.set(arr, "I am some number")

// Get a reference to the same `arr` whose key you set previously:
const arrKey = [...map.keys()].find(
  key => Array.isArray(key) && JSON.stringify(key) === JSON.stringify([0, 1, 2, 3])
);
console.log(map.get(arrKey));

(but this is a pretty ugly thing to have to do - if you find yourself having to do this, usually it'd be better to use a different data structure)

Upvotes: 0

Related Questions