
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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' }
- Related Articles
- Javascript search for an object key in a set
- How to call the key of an object but return it as a method, not a string in JavaScript?
- How to set an object key inside a state object in React Hooks?
- How to automate this object using JavaScript to set one key on each iteration as null?
- JavaScript - Set object key by variable
- How to clone a js object except for one key in javascript?
- How to pass an object as a parameter in JavaScript function?
- JavaScript: How to Create an Object from Key-Value Pairs
- JavaScript: How to Check if a String is a Literal or an Object?
- How can we use a JavaScript function as an object?
- How to convert a string to JavaScript object?
- How to access an object value using variable key in JavaScript?
- How to convert a JavaScript date object to a string?
- Code to construct an object from a string in JavaScript
- How to sort an object in ascending order by the value of a key in JavaScript?

Advertisements