Andy Bas Andy Bas - 1 year ago 91
Javascript Question

JavaScript property accessors wrapped in array

I'm failing to find documentation as to how/why the following works:

const data = {one: 1, two: 2}
const key = ['one']

data[key[0]] // 1
data[key] // 1
data[[key]] // 1
data[[[key]]] // 1
data[[[[key]]]] // 1
data[['one', 'two']] // undefined

What allows any number of square brackets to surround the key and still successfully find the key in the object? Is there specific behavior when
array.length === 1
? And if so, where can I find documentation or clarity on that?

Answer Source

When using the object[key] bracket notation to access properties, the key is converted to a string.* The string representation of an array is the string representations of its elements joined with ,. For a one-element array, that's the same as the string representation of its only element.

var foo = { 'a,b': 2 };
console.log(foo[['a', 'b']]); // 2;

* Or a symbol.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download