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.
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.
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
obj[foo] is doing obj[foo.toString()]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"}