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 set JavaScript object values dynamically?
JavaScript objects allow dynamic property assignment using bracket notation or dot notation. This enables you to set object values at runtime based on variables or user input.
Syntax
// Using dot notation object.propertyName = value; // Using bracket notation (dynamic) object[propertyName] = value; object['property name'] = value;
Method 1: Using Dot Notation
Dot notation works when you know the property name at compile time:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dynamic Object Values</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
margin: 20px 0;
}
</style>
</head>
<body>
<button class="btn">Update Student Info</button>
<h3>Click the button to see dynamic property updates</h3>
<script>
let resEle = document.querySelector(".result");
let btnEle = document.querySelector(".btn");
let student = {
name: "Rohan",
age: 22,
displayInfo() {
return `Name: ${this.name}, Age: ${this.age}`;
}
};
btnEle.addEventListener("click", () => {
resEle.innerHTML = "Original: " + student.displayInfo() + "<br><br>";
// Using dot notation
student.name = "Shawn";
student.age = 19;
student.grade = "A+"; // Adding new property
resEle.innerHTML += "After Update: " + student.displayInfo() + "<br>";
resEle.innerHTML += "Grade: " + student.grade;
});
</script>
</body>
</html>
Method 2: Using Bracket Notation (Dynamic Keys)
Bracket notation allows property names to be determined at runtime:
<!DOCTYPE html>
<html>
<head>
<style>
.result {
font-size: 16px;
margin: 20px 0;
padding: 10px;
background: #f5f5f5;
}
</style>
</head>
<body>
<h2>Dynamic Property Assignment</h2>
<button onclick="updateDynamic()">Set Dynamic Properties</button>
<script>
function updateDynamic() {
let person = {};
let properties = ['firstName', 'lastName', 'email'];
let values = ['John', 'Doe', 'john@email.com'];
// Dynamic assignment using variables
for(let i = 0; i < properties.length; i++) {
person[properties[i]] = values[i];
}
// Adding computed property name
let key = 'full' + 'Name';
person[key] = person.firstName + ' ' + person.lastName;
document.querySelector('.result').innerHTML =
JSON.stringify(person, null, 2).replace(/<br>/g, '<br>').replace(/ /g, ' ');
}
</script>
</body>
</html>
Using Variables as Property Names
<!DOCTYPE html>
<html>
<body>
<script>
let config = {};
let userInput = 'theme';
let settingValue = 'dark';
// Dynamic property assignment
config[userInput] = settingValue;
config['language'] = 'JavaScript';
// Using computed property names (ES6)
let newConfig = {
[userInput]: settingValue,
['api' + 'Key']: 'secret123'
};
document.getElementById('output').innerHTML =
'Config: ' + JSON.stringify(config) + '<br>' +
'New Config: ' + JSON.stringify(newConfig);
</script>
</body>
</html>
Comparison
| Method | Use Case | Dynamic Keys | Syntax |
|---|---|---|---|
| Dot Notation | Known property names | No | obj.prop = value |
| Bracket Notation | Dynamic/computed names | Yes | obj[key] = value |
| ES6 Computed | Object literals | Yes | {[key]: value} |
Common Use Cases
- Form Data Processing: Setting object properties based on form field names
- API Response Mapping: Dynamically assigning values from API responses
- Configuration Objects: Building settings objects from user preferences
- Dynamic Property Names: Creating properties with computed or variable names
Conclusion
Use dot notation for known properties and bracket notation for dynamic property assignment. Bracket notation provides flexibility when property names are determined at runtime or contain special characters.
Advertisements
