Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to set a String as a key for an object - 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.
Using Computed Property Names (ES6)
The most modern approach is using computed property names with bracket notation inside the object literal. This allows you to dynamically set keys during object creation.
Syntax
const keyName = "propertyName";
const object = { [keyName]: 'value' };
Example
const keyName = 'username';
const stringToObject = { [keyName]: 'Johny John' };
console.log(stringToObject);
// Multiple dynamic keys
const userType = 'admin';
const statusKey = 'isActive';
const user = {
[keyName]: 'Alice',
[userType]: true,
[statusKey]: false
};
console.log(user);
{ username: 'Johny John' }
{ username: 'Alice', admin: true, isActive: false }
Using Bracket Notation After Creation
You can also add properties with string keys after the object is created using bracket notation. This is useful for conditional property assignment.
Example
const key = "favoriteColor";
const person = {};
person[key] = "Blue";
person["age"] = 25;
console.log(person);
// Dynamic key from user input simulation
const dynamicKey = "hobby-" + Date.now();
person[dynamicKey] = "Reading";
console.log(person);
{ favoriteColor: 'Blue', age: 25 }
{ favoriteColor: 'Blue', age: 25, 'hobby-1703123456789': 'Reading' }
Comparison of Methods
| Method | When to Use | ES6 Support |
|---|---|---|
Computed Property Names {[key]: value}
|
Object creation with dynamic keys | Yes |
Bracket Notation obj[key] = value
|
Adding properties after creation | Always supported |
Practical Use Case
// Building configuration object dynamically
const config = {};
const environment = 'production';
const dbKey = `${environment}_database_url`;
config[dbKey] = 'mongodb://prod-server:27017';
config['app_name'] = 'My Application';
console.log(config);
// Creating object with dynamic keys from array
const settings = ['theme', 'language', 'timezone'];
const userPreferences = {};
settings.forEach((setting, index) => {
userPreferences[setting] = `default_${index}`;
});
console.log(userPreferences);
{ production_database_url: 'mongodb://prod-server:27017', app_name: 'My Application' }
{ theme: 'default_0', language: 'default_1', timezone: 'default_2' }
Conclusion
Setting strings as object keys in JavaScript is essential for dynamic programming. Use computed property names for object creation and bracket notation for adding properties later. Both methods provide the flexibility needed for building dynamic, data-driven applications.
