nottheonion
nottheonion

Reputation: 9

Object property overwrites

Doing a tutorial...came across:

let user1 = { name: 'Bob' };
let user2 = { name: 'Ross' };
let total = {};
total[user1] = 5;
total[user2] = 42;

Why does total user1 get overwritten to 42? I imagine this all looking like this now:

total = {{ user1 = { name: 'Bob' } : 5}, { user2 = { name: 'Ross' } : 42 };

So total contains two object properties which map to value 5 and 42? How do you access the name properties in total[user1] and total[user2]? Also, why does 42 overwrite the 5? I can't see exactly what's happening.

Upvotes: 1

Views: 58

Answers (1)

Michael Hulet
Michael Hulet

Reputation: 3499

In JavaScript, when you attempt to use an object as a key for another object, the object meant to be a key is first converted to a string by calling toString on that object. Unless overridden, toString on every object always returns "[object Object]". So, when you use any object as a key, you're instead using the string "[object Object]" for all objects which haven't defined their own toString method, as is the case in your example. When you assign to a key in an object, it overwrites whatever previous value it had, and so you get the result you see. If you'd like this to be different for an object, you can overwrite the toString method to return something different, for example:

const example = {test: "This is a test"};
const overwritten = {test: "This is a test"};
overwritten.toString = function(){
                           return '{test: "This is a test"}';
                       };
let all = {};
all[example] = 1;
all[overwritten] = 2;

// all == {"[object Object]": 1, '{test: "This is a test"}': 2}

Upvotes: 1

Related Questions