In JavaScript, you can dynamically add a property to an object using a variable as the name. This allows you to create flexible and dynamic objects based on runtime values, enhancing code reusability and adaptability.
There are several methods that can be used to add a property to a JavaScript object using a variable as the name.
- Using Dot Notation
- using Object.assign()
- Using ES6 Computed Property Names
Approach 1: Using Dot Notation
Using dot notation with square brackets, you can add a property to a JavaScript object using a variable as the name, making it accessible and modifiable directly through the object.
Example: in this example, Object object1 has properties firstname and lastname. We add a property named age with value 25 using dot notation.
Javascript
let object1 = { firstname: "Romy" , lastname: "Kumari" }; // Step 1: Define the property name and value const newPropertyName = 'age' ; const newPropertyValue = 25; // Step 2: Add the new property using dot notation object1[newPropertyName] = newPropertyValue; // Step 3: Access and //display the updated object console.log(object1); |
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }
Approach 2: using Object.assign()
Using Object.assign(), the new object is created by merging existing object1 with new property { [newPropertyName]: newPropertyValue }. The original object remains unchanged.
Example:
Javascript
let object1 = { firstname: "Romy" , lastname: "Kumari" }; // Step 1: Define the property name and value const newPropertyName = 'age' ; const newPropertyValue = 25; // Step 2: Add the new property using Object.assign() const updatedObject = Object.assign({}, object1, { [newPropertyName]: newPropertyValue }); // Step 3: Access and display the updated object console.log(updatedObject); |
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }
Approach 3: Using ES6 Computed Property Names:
ES6 introduces computed property names, which allows you to use variables to set property names directly when defining an object.
Example: in this example, A new object is created by spreading object1 properties and adding a property named ‘age’ with the value 25.
Javascript
const propertyName = 'age' ; const propertyValue = 25; const object1 = { firstname: "Romy" , lastname: "Kumari" }; // Add the new property using ES6 Computed Property Names const updatedObject = { ...object1, [propertyName]: propertyValue, }; // Access and display the updated object console.log(updatedObject); |
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }