Ealon
Ealon

Reputation: 4898

Why are object keys converted to "[object Object]"?

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 and c will both be converted to "[object Object]"

Can someone explain why this is?

Upvotes: 1

Views: 820

Answers (3)

Oleksandr T.
Oleksandr T.

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

Ramziddin Makhmudov
Ramziddin Makhmudov

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

Paul Roub
Paul Roub

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

Related Questions