- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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