Reputation: 4898
This code:
var a = {},
b = {key:'b'},
c = {key:'c'};
a[b] = 111;
a[c] = 222;
console.log(a[b]);
Outputs: "222" (not "111").
Explanation:
b
andc
will both be converted to "[object Object]"
Can someone explain why this is?
Upvotes: 1
Views: 820
Reputation: 77482
When you use Object
as key - Object
(for example b
) is converted to String
(with toString
method. keys are always converted to strings) and then you will have only one key in object a
- it will be [object Object]
,
a['[object Object]'] = 111;
a['[object Object]'] = 222;
You should set unique keys, like this
var a = {};
var b ={key:'b'};
var c ={key:'c'};
a[b.key] = 111;
a[c.key] = 222;
console.log(a.b);
console.log(a.c);
Upvotes: 1
Reputation: 114
Here you are referring to objects a
and b
, but instead of returning you a whole object with its keys and values it instead returns you a string - that says [object...
- it is an object ...Object]
- type of Object. It could be [object Function]
, [object Number]
etc...
So here you are getting two times [object Object]
, so you are overwriting the key.
If you would write:
a[c] = 222;
a[b] = 111;
The output would be: 111
Upvotes: 0
Reputation: 36438
[object Object]
is just the string representation of an object -- that is, the result of calling b.toString()
or c.toString()
.
Object keys are always strings, so when you say:
a[b]
JS will find the string representation of b
([object Object]
), and use that. Same with c
.
Upvotes: 3