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'


Following is the complete code −

const keyName = 'username';
const stringToObject = {
   [keyName]: 'David Miller'
console.log("Your String Value="+keyName);
console.log("Your Object Value=")

To run the above program, use the following command −

node fileName.js.

Here, my file name is demo238.js.


The output is as follows −

PS C:\Users\Amit\javascript-code> node demo238.js
Your String Value=username
Your Object Value=
{ username: 'David Miller' }

Updated on: 03-Oct-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started