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
Selected Reading
How to create an object property from a variable value in JavaScript?
JavaScript has two notations for creating object properties: dot notation and bracket notation. To create an object property from a variable value, you need to use bracket notation or ES6 computed property names.
Method 1: Using Bracket Notation (Dynamic Assignment)
You can assign properties to existing objects using bracket notation with variable names:
const obj = {a: 'foo'};
const prop = 'bar';
// Set the property using the variable name prop
obj[prop] = 'baz';
console.log(obj);
{ a: 'foo', bar: 'baz' }
Method 2: Using ES6 Computed Property Names
ES6 introduces computed property names, allowing you to use variables as keys during object literal creation:
const prop = 'bar';
const obj = {
// Use literal string as key
a: 'foo',
// Use the value of prop variable as key
[prop]: 'baz'
};
console.log(obj);
{ a: 'foo', bar: 'baz' }
Method 3: Using Variables for Both Key and Value
You can use variables for both property names and values:
const keyName = 'username';
const keyValue = 'john_doe';
const status = 'active';
const user = {
[keyName]: keyValue,
[status]: true,
id: 123
};
console.log(user);
{ username: 'john_doe', active: true, id: 123 }
Comparison
| Method | When to Use | Syntax |
|---|---|---|
| Bracket Notation | Adding properties after object creation | obj[variable] = value |
| Computed Property Names | During object literal creation | {[variable]: value} |
Conclusion
Use bracket notation for dynamic property assignment after object creation, and ES6 computed property names when defining objects with variable keys. Both methods provide flexibility in JavaScript object manipulation.
Advertisements
