Was it helpful?

Question

How to set a String as a key for an object - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' }
raja
Published on 03-Oct-2020 18:50:25
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top