Access object properties using computed property names
P粉578680675
2023-08-20 15:32:14
<p>I am trying to access the properties of an object using dynamic names. Is this possible? </p>
<pre class="brush:php;toolbar:false;">const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar and get "Foobar!"</pre>
<p><br /></p>
This is my solution:
Usage example:
There are two ways to access object properties: Dot notation : something.bar and square bracket notation: something['bar'].
The value in the square brackets can be any expression. Therefore, if the property name is stored in a variable, square bracket notation must be used: