0

Currently, we're calling a 3rd party service with the following JavaScript object:

props = { ['356']: false, ['456']: true}

I notice that when I enter it into the Chrome browser console and re-inspect the object I get the following output:

props = { 356: false, 456: true}

What is going on here? Is '356' still a string after apparently being automatically casted from an object key that is an array of one string? It looks like it automatically got converted to an integer.

laruiss
  • 3,477
  • 1
  • 14
  • 27
Nona
  • 4,534
  • 6
  • 27
  • 57
  • You can put any valid expression as object keys when you enclose them in `[]`. `['356']` translates to `365`. https://stackoverflow.com/a/25333702/1927991 – codemonkey Jan 18 '21 at 18:42
  • 1
    Yes, it's still a string. Just like in `{propName: true}` the `propName` is a string. JavaScript objects do not have numeric property keys. – Bergi Jan 18 '21 at 18:44
  • 2
    "*an object key that is an array of one string*" - no, it's not, it's a [computed property](https://stackoverflow.com/q/34831262/1048572), with a string literal as the dynamic expression. – Bergi Jan 18 '21 at 18:45

2 Answers2

0

['356'] when used as an object key is not an array, it's using computed properties, hence the conversion to the string '356'. Object keys are strings. You can test this with other types, for example in {[function(){}]: 1} they key is the string 'function(){}'. If for whatever reason you need an array representation, you can call JSON.stringify, though that will give you back a JSON string with an array, not an array itself:

const foo  = { [JSON.stringify(['foo'])]: 1}
// "[\"foo\"]": 1
Zac Anger
  • 3,159
  • 1
  • 9
  • 29
0

Keys in object is always string. Next syntax isn't about array:

props = { ['356']: false, ['456']: true}

Values in [...] is calculated in runtime, so:

props = { [5 + 6]: false, ['a' + 'b']: true}

is the same as:

props = { '11': false, 'ab': true}
Murashki
  • 1
  • 1