Home > Article > Web Front-end > How Can I Use Dynamic Property Names in JavaScript Object Literals?
In JavaScript, object properties are typically accessed using dot notation or bracket notation. While the former only accepts string literals as property names, the latter offers increased flexibility.
The bracket notation allows the use of variables as property names within an object literal. This is achieved through computed property names, a feature introduced in ES6.
<code class="javascript">const myVar = "name"; const myObject = { [myVar]: "value" };</code>
In the above example, myVar is used as the property name within the object literal using square brackets. This is equivalent to using the following traditional approach:
<code class="javascript">const myObject = { name: "value" };</code>
It is important to note that computed property names cannot be used within object literals themselves. To dynamically define property names for an object literal, the object must first be created, and individual properties can then be assigned using bracket notation.
<code class="javascript">const myObject = {}; const myVar = "name"; myObject[myVar] = "value";</code>
This allows for greater control over the property names within an object.
The above is the detailed content of How Can I Use Dynamic Property Names in JavaScript Object Literals?. For more information, please follow other related articles on the PHP Chinese website!