0

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?

Tân
  • 1
  • 15
  • 56
  • 102
  • 4
    Before assigning the `key`, make it `JSON.stringify`... I am really curious about how you came across such use-case... – Rayon Aug 24 '16 at 05:55
  • 5
    "when the key is an object"?? Keys are _always strings_, though a string may look like an object. – Teemu Aug 24 '16 at 05:56
  • When you do this: `obj2[obj1] = 2` it converts `obj1` into a new string value in exactly the same way that `console.log()` does to produce `"[object Object]"`. So what you're doing is equivalent to `obj2["[object Object]"] = 2`. When you literally do the same thing later you're just replacing the value - not adding a new one – Tibrogargan Aug 24 '16 at 06:01
  • 3
    [_Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the `toString` method._](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Property_names) – Rayon Aug 24 '16 at 06:05
  • @Teemu Can you edit my question title? – Tân Aug 24 '16 at 07:03

2 Answers2

1

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.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • [_MDN Reference_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Property_names) – Rayon Aug 24 '16 at 06:06
0

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.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392