Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird behaviour when using objects as keys in Javascript

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?

like image 370
Soggiorno Avatar asked Jul 22 '26 10:07

Soggiorno


1 Answers

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)

like image 178
CertainPerformance Avatar answered Jul 24 '26 00:07

CertainPerformance