Tân
Tân

Reputation: 1

Get key of an object when the key is an object

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

Answers (2)

Amadan
Amadan

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 }.

  1. You can't get what isn't there.

  2. Because it isn't an object.

  3. No, it isn't.

  4. {}.toString() is same as ({ 1: 1 }).toString(), so... you can see where this leads.

Upvotes: 1

Nina Scholz
Nina Scholz

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

Related Questions