In JavaScript, you can dynamically add a property to an object by using a variable as the property name. This allows objects to be created or updated based on values determined at runtime.
- Uses a variable to dynamically define the property name.
- Allows properties to be added or updated at runtime.
- Supports both modifying the existing object and creating a new object.
- Computed property names provide a concise way to define dynamic properties.
Approach 1: Using Bracket Notation
Bracket notation allows a variable to be used as the property name when adding a property to an object. The value stored in the variable becomes the actual property name.
Example: Adds an age property to the object using a variable as the property name.
let object1 = {
firstname: "Romy",
lastname: "Kumari"
};
// Define the property name and value
const newPropertyName = "age";
const newPropertyValue = 25;
// Add the new property using bracket notation
object1[newPropertyName] = newPropertyValue;
console.log(object1);
Output
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }
Note: Bracket notation modifies the original object directly.
Approach 2: Using Object.assign()
The Object.assign() method can be used to create a new object by merging the existing object with a dynamically named property. The original object remains unchanged.
Example: Creates a new object with an age property using Object.assign().
const object1 = {
firstname: "Romy",
lastname: "Kumari"
};
// Define the property name and value
const newPropertyName = "age";
const newPropertyValue = 25;
// Add the new property using Object.assign()
const updatedObject = Object.assign(
{},
object1,
{ [newPropertyName]: newPropertyValue }
);
console.log(updatedObject);
Output
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }
Note: Since {} is passed as the first argument, Object.assign() creates a new object without modifying object1.
Approach 3: Using ES6 Computed Property Names
ES6 computed property names allow variables to be used as property names inside an object literal. The property name is placed inside square brackets ([]).
Example: Uses a computed property name with the spread operator to create an updated object.
const propertyName = "age";
const propertyValue = 25;
const object1 = {
firstname: "Romy",
lastname: "Kumari"
};
// Add the new property using a computed property name
const updatedObject = {
...object1,
[propertyName]: propertyValue
};
console.log(updatedObject);
Output
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }
Note: This approach creates a new object and leaves the original object1 unchanged.