Consider the following snippet:
var a = {amount: 300}
var b = {amount: 250}
var c = {[a] : 'bla', [b]: 'blabla'};
console.log(c[a]);
It prints:
blabla
But should it not print:
bla
What is going on here?
Objects cannot have other objects as their keys. What's happening is, since the a is an invalid key, its toString method is called, thus converting a into a string. The same thing happens with [b]. So, to the interpreter, what you're doing actually looks something like this:
var a = {amount: 300}
var b = {amount: 250}
var c = {['object Object'] : 'bla', ['object Object']: 'blabla'};
console.log(c);
If you wanted to use objects as keys, you should use a Map instead:
var a = {amount: 300}
var b = {amount: 250}
var c = new Map()
.set(a, 'bla')
.set(b, 'blabla');
console.log(c.get(a));
(Maps can have anything as their keys)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With