Could you use Javascript objects as keys to another object?

Artem Dracontis
Feb 4, 2019 · 1 min read

No, you can’t. I’ve got an example for you:

var a={},
b={key:'b'},
c={key:'c'};
a[b]=123;
a[c]=456;
console.log(a[b]);
console.log(a[c]);

Output of both console.log statements will be 456. To understand why it it so, we should use base Object method toString() on both objects. We will see following output:

> b.toString();
< "[object Object]"
> c.toString();
< "[object Object]"

So when you use object as a key of another object it internally converts to string with value [object Object]. So this is all equal calls:

a[b] === a[c] === a[{}] === a["[object Object]"]

But if you still want to use object as a key, you should use ES6 Maps.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store