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 ignore using variable name as a literal while using push() in JavaScript?
To avoid using a variable name as a literal string when pushing objects to an array, use square brackets [variableName] for computed property names. This allows the variable's value to become the property key.
The Problem with Literal Property Names
When you use name: value in an object, "name" becomes a literal string property, not the variable's value:
var name = "David";
var data = [];
// This creates a property literally named "name"
data.push({ name: "This will always be 'name' property" });
console.log(data);
[ { name: 'This will always be 'name' property' } ]
Solution: Using Computed Property Names
Use square brackets [variableName] to use the variable's value as the property key:
var name = "David";
var putTheAllData = [];
// Literal property name - "name" as string
putTheAllData.push({ name: "The property key is literally 'name'" });
// Computed property name - uses variable's value
putTheAllData.push({ [name]: "The property key is the value of variable 'name'" });
console.log(putTheAllData);
[
{ name: 'The property key is literally 'name'' },
{ David: 'The property key is the value of variable 'name'' }
]
Multiple Variables Example
var firstName = "John";
var lastName = "Smith";
var age = "25";
var userData = [];
// Using computed property names for all variables
userData.push({ [firstName]: "First name value" });
userData.push({ [lastName]: "Last name value" });
userData.push({ [age]: "Age value" });
console.log(userData);
[
{ John: 'First name value' },
{ Smith: 'Last name value' },
{ '25': 'Age value' }
]
Comparison
| Method | Syntax | Property Key |
|---|---|---|
| Literal | { name: value } |
String "name" |
| Computed | { [name]: value } |
Variable's value |
Conclusion
Use square brackets [variableName] for computed property names when you want the variable's value as the property key, not the variable name itself. This ES6 feature provides dynamic object property creation.
Advertisements
