Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript property accessors wrapped in array [duplicate]

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?

like image 427
Andy Bas Avatar asked Jun 24 '26 17:06

Andy Bas


1 Answers

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.

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

* Or a symbol.

like image 95
Ry- Avatar answered Jun 26 '26 06:06

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!