Add a Property to JavaScript Object Using a Variable as the Key
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.
[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.
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);
Output
{ 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.
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);
Output
{ 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.
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);
Output
{ firstname: 'Romy', lastname: 'Kumari', age: 25 }