Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using object as ES2015 map key

I've been trying to get a hold of ES2015 map concept and one thing I don't understand is the following:

var mapRawObj = new Map();
var rawObj = {j:"I like penguin"};
mapRawObj.set(rawObj,true);
console.log(mapRawObj.get(rawObj)); //this outputs true

mapRawObj.set({j:"I like polar bear"},true);
console.log(mapRawObj.get({j:"I like polar bear"})); //this outputs undefined

The first one works, the second one doesn't, and I don't understand why?

I thought when you register object as key, it's the object itself, not the object's name. That's why in the below example when you re-assign the key object, it fails as key?

var obj = { a:"hello ", b:"world "};
var mapObj = new Map();
mapObj.set(obj,true);
obj = {d:34}; //obj is re-assigned
console.log(mapObj.get(obj)); // outputs undefined
like image 247
bastole Avatar asked May 19 '26 00:05

bastole


1 Answers

Objects with the same data are not equal in Javascript, ie

{ hello: 'world'} === { hello: 'world'} // false

The first example uses the same object as the key for set and get, so the key is identical:

var obj = { hello: 'world'};
obj === obj // true

But the second example creates a new object for the get(), which is not identical to the key used to set the value in the map. Since it's not identical, the map doesn't have anything set against this new key and returns undefined.

Even though the new key has exactly the same data as the original key, the objects aren't referring to the same data internally.

More on object equality

like image 154
whostolemyhat Avatar answered May 20 '26 13:05

whostolemyhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!