How to set a String as a key for an object - JavaScript?
https://www.tutorialspoint.com/how-to-set-a-string-as-a-key-for-an-object-javascript
Question
How to set a String as a key for an object - JavaScript?
Let’s say the following is our string −
const keyName = 'username';
To set a string as a key for an object, use the [] and pass the string name −
const stringToObject = { [keyName]: 'David Miller' };
Example
Following is the complete code −
const keyName = 'username'; const stringToObject = { [keyName]: 'David Miller' }; console.log("Your String Value="+keyName); console.log("Your Object Value=") console.log(stringToObject);
To run the above program, use the following command −
node fileName.js.
Here, my file name is demo238.js.
Output
The output is as follows −
PS C:\Users\Amit\javascript-code> node demo238.js Your String Value=username Your Object Value= { username: 'David Miller' }
Advertisements
Not affiliated with Tutorialspoint