roro
roro

Reputation: 213

Javascript object Map, how to get key from value if multiple keys map to same value

I'm not sure if understand JavaScript Object Maps correctly and can't figure out if something is an error or if that's how it is.

In code below I can understand first 3 console messages.

But should the last console.log - show nothing?

let key1 = 3;
let key2 = 6;
let key3 = 14;
let myMap= new Map();

myMap.set(key1, 'Buy');
myMap.set(key2, 'Buy');
myMap.set(key3, 'Sell');

console.log(myMap.get(key1));   // Buy
console.log(myMap.get(key2));   //Buy 
console.log(myMap.get(key3));   //Sell
console.log(myMap.get('Buy'));   //.....nothing

The MDN page says: "Any value (both objects and primitive values) may be used as either a key or a value." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

So, from what I understand, 'Buy' which is a value, should map to both key1 & key2.

Can someone confirm the reason for this behavior? Thanks

Upvotes: 0

Views: 108

Answers (1)

aquinas
aquinas

Reputation: 23796

No, what they mean is that you can use any object as a key in the map, and you can store any object as a value in the map. It doesn't mean that values are also keys. That would be a weird, unexpected, and unwanted behavior.

Upvotes: 2

Related Questions