Reputation: 1
let obj1 = {
1: 1
};
let obj2 = {};
obj2[obj1] = 2;
let keys = Object.keys(obj2);
// first
for (let key of keys) {
console.log(key) // [object Object]
}
for (let prop in obj2) {
console.log(prop) // [object Object]
}
let key = keys[0];
// second
console.log(typeof key); // string
console.log(JSON.stringify(key) === JSON.stringify(obj1)); // false
// thirth
console.log(obj2['[object Object]']); // 2
obj2[{}] = 3;
// fourth
console.log(obj2['[object Object]']); // 3
console.log(obj2[obj1]); // 3
I have 4 questions:
1/. In the first: is there a way to get object
{
1: 1
}
instead of [object object]
?
2/. In the second: why am I getting string
when trying to get the type of an object (not object
)?
3/. In the thirth: the key of an object is an object. So, why can I assign it via a string?
4/. In the fourth: after adding another object to obj2
, obj1
has been overridden although {}
is different from obj1
(not duplicate key). Why?
Upvotes: 0
Views: 86
Reputation: 198314
JavaScript objects can only use strings for keys. Thus, obj2[obj1] = 2
is equivalent to obj2[obj1.toString()] = 2
; and obj1.toString()
is "[object Object]"
. Thus, your obj2
is, in fact, { "[object Object]": 2 }
.
You can't get what isn't there.
Because it isn't an object.
No, it isn't.
{}.toString()
is same as ({ 1: 1 }).toString()
, so... you can see where this leads.
Upvotes: 1
Reputation: 386550
Why not use Map
instead of an object.
The Map object is a simple key/value map. Any value (both objects and primitive values) may be used as either a key or a value.
Upvotes: 0