Tushar Roy
Tushar Roy

Reputation: 239

Using Obejct as key inside an object

Is it possible to use object as a key inside an object?

I found the answer to be NO but with no clear explaination.
Example:

let user1 = { name: "John Doe" };
let numberOfAnswers = {}; // try to use an object

numberOfAnswers[user1] = 234; // try to use user1 object as the key
alert(numberOfAnswers) // [object][object]

But then what are we doing here? Why this seems to work? Are we not creating numberOfAnswers Object with user1 as key?

let numberOfAnswers = {
   user1: {
      visits: 123;
   }
} 

Upvotes: 1

Views: 54

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074979

Is it possible to use object as a key inside an object?

No. Property keys are always strings or Symbols, never objects. If you use an object as a property key, it's implicitly converted to a string (usually) or Symbol (if the object overrides the "to primitive" operation).

You can use objects as keys in Map instances, though.

But then what are we doing here? Why this seems to work? Are we not creating numberOfAnswers Object with user1 as key?

let numberOfAnswers = {
   user1: {
      visits: 123;
   }
} 

No. You're creating an object with a property whose key is the string "user1" and whose value is an object.

Upvotes: 2

Related Questions