0
var foo = {prop:1};
var bar = {prop:2};
var obj = {};
obj[foo] = 'value';
console.log(obj[bar]); //'value'

It is quite confusing why obj[bar] and obj[foo] are same now, whereas foo and bar are not same.

2

1 Answer 1

8

because

obj[foo]='value';

is the same as

obj["[object Object]"]='value';

Object keys are string so it's internally doing foo.toString()

and foo.toString() === bar.toString()

Every objects will return "[object Object]" if used as a key (not talking about arrays, numbers, strings..)


You'll need something that uniquely identify your objects, like below

var foo = {id:"foo", prop:1};
var bar = {id:"bar", prop:2};
var obj = {};
obj[foo.id] = 'value';
console.log(obj[bar.id]); //undefined
Sign up to request clarification or add additional context in comments.

3 Comments

Its a implicit behaviour obj[foo] is doing obj[foo.toString()]
I will create a new object - var cc= new Object() then console.log(obj[cc]); //value Conclusion: here object cc will be converted to "[object Object]". here if I will look obj in console- Object {[object Object]: "value"}
@jiten as stated in my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.