Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an object as a property key in JavaScript

Tags:

javascript

What is going on in this code?

var a = {a:1};
var b = {b:2};
var c = {};

c[a] = 1;
c[b] === 1 // true!

c[b] = 2;
c[a] === 2 // true!

Specifically, why does using looking up b in c return the value that was stored in a property of a?

What does it mean to use an object as a key to a property in JavaScript?

I've tested this in Chrome/Node and in Firefox.

like image 897
Drew Noakes Avatar asked Sep 12 '12 10:09

Drew Noakes


People also ask

Can you use an object as a key JavaScript?

Can you use objects as Object keys in JavaScript? # The short answer is "no". All JavaScript object keys are strings.

Can a JavaScript object have a function as a property?

Methods—setting functions as properties of objects. In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.

Can I use object as key in Map JavaScript?

Introduction to JavaScript Map object A key of an object must be a string or a symbol, you cannot use an object as a key. An object does not have a property that represents the size of the map.


1 Answers

What does it mean to use an object as a key to a property in JavaScript?

Javascript objects only allow string keys, so your object will first be coerced to a string.

Specifically, why does using looking up b in c return the value that was stored in a property of a?

The string representation of {a: 1} and {b: 2} are both "[object Object]", thus, the property is overwritten.

Edit: If you really need to use objects as keys (I would prefer another solution, if possible), you could use the object's JSON representation:

c[JSON.stringify(a)] = 1
c[JSON.stringify(b)] = 2

But, again, try to think of a different approach. Perhaps the objects have unique identifiers other than the object itself.

like image 138
Linus Thiel Avatar answered Sep 20 '22 19:09

Linus Thiel