
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set a String as a Key for an Object in JavaScript
In JavaScript, it is common to use a string as a key for an object, especially when you want to dynamically create or change the properties of the object. Objects are fundamental data structures that allow you to store collections of data in key-value pairs. You can use strings as keys directly. It is a simple and straightforward method. This article will guide you how to use a string as a key for an object.
Setting a String as a Key for an Object
You can set a strings as a key for an object using bracket notation. The bracket notation allows you to use any string as a key for an object. If the key name is stored in a variable as a string, you can directly pass that string inside [](square brackets).
Here is the syntax for this:
const key="keyname" const object={[keyname]: 'value'};
Example
The following is a simple example for this:
keyName = 'username'; const stringToObject = { [keyName]: 'Johny John' }; console.log(stringToObject);
Output
{ username: 'Johny John' }
You can also use the bracket notation for setting a string as key in the following form. Here is the syntax for this:
const keyName = 'username'; const key="keyname" const object={}; object[key]="value";
Example
The following is a simple example for this:
const key = "favoriteColor"; const person = {}; person[key] = "Blue"; console.log(person);
Output
{ favoriteColor: 'Blue' }
Conclusion
Setting a string as a key for an object in JavaScript is straightforward and flexible. In this article, we have seen simple and efficient way of setting string as a key of an object. By understanding these concept, you can effectively use strings as keys in JavaScript objects and build more dynamic, flexible code.