0

From what I've learned, javascript allows any type to a value of an key inside an object like:

{
  key1: "string",
  key2: ["list"],
  key3: 123,
  key4: { name: "string embedded in an object in another object"}
}

But it only allows certain certain types for the keys like string and integers: { "string": "string", 123: "integer" }

I came across this when I wrote the below code this and the key ended up being: [object Object]

let a = {}
let b = {}

b.name = {name: "name"}

a[b.name] = "value"

console.log(JSON.stringify(a))

Result from above:

{"[object Object]":"value"}

So what types are allowed for keys in objects in js?? And why does it show the key as [object Object]?

isethi
  • 661
  • 1
  • 10
  • 22
  • Does this answer your question? [Keys in Javascript objects can only be strings?](https://stackoverflow.com/questions/6066846/keys-in-javascript-objects-can-only-be-strings) – norbitrial Apr 03 '20 at 14:47

3 Answers3

3

You are mixing two different concepts. JSON and JavaScript objects–although similar–are not the same. You can read about the difference between JSON and the Object Literal Notation.

  • JSON has a limited grammar and properties can only be strings.
  • A JavaScript Object's "key value is either a String or a Symbol value". You can find more information in this question.

And why does it show the key as [object Object]?

Because keys can only be strings or symbols. Any other value is coerced to a string (e.g. by calling the value's toString method if available). ({}).toString() returns "[object Object]"`.

If you want to use objects as keys, you can use a Map.

str
  • 42,689
  • 17
  • 109
  • 127
1

If you try running this it will output value and if you print the key type it will be string

let a = {}
let b = {}

b.name = {name: "name"}

a[b.name] = "value"

console.log(a['[object Object]'])
for (key in a) {
    console.log(typeof key);
    //-> "string"
}

Javascript makes the key a string before saving it.

Similar question has been answered before: https://stackoverflow.com/a/3608275/12703377

Victor Timofei
  • 334
  • 4
  • 13
1

The key of a object can be only a string or a symbol. When you put an object into [] operator, the string representation of that object is used as a key.

let a = {}
let b = {
    toString: function(){return "B string representation"}
}
a['attribute'] = 'value'
a[b] = 'value'
a[2] = 'value'
Object.keys(a)

result

(3) ["2", "attribute", "B string representation"]

Off your question... looking at your code, what you probably want to do is

let a = {}
let b = {}
b.name = "name"
a[b.name] = "value"
console.log(JSON.stringify(a))
Charlestone
  • 1,248
  • 1
  • 13
  • 27