In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array, Dynamic values and objects in JavaScript allow changing, accessing, or creating values and object properties at runtime for flexibility and adaptability.
There are several methods that can be used to create dynamic values and objects in JavaScript.
- Using object literals with computed property names
- Using the bracket notation for object property assignment
- Using the spread operator
Approach 1: Using object literals with computed property names
In this approach we are using object literals with computed property names that allow you to dynamically create or modify object properties based on variables or expressions within square brackets [].
Syntax:
const dynamicObject = {
[dynamicKey]: dynamicValue,
};
Example: In this example, we are using the above-explained approach.
Javascript
const dynamicKey1 = 'age' ; const dynamicValue1 = 25; const dynamicKey2 = 'city' ; const dynamicValue2 = 'Noida' ; const dynamicObject = { name: 'Aman' , [dynamicKey1]: dynamicValue1, [dynamicKey2]: dynamicValue2, }; console.log(dynamicObject); |
{ name: 'Aman', age: 25, city: 'Noida' }
Approach 2: Using the bracket notation for object property assignment
In this approach we are using bracket notation for object property assignment allows you to set or add properties to an object dynamically.
Syntax:
obj[propertyName] = propertyValue;
Example: In this example, we are using the above-explained approach.
Javascript
const dynamicKey = 'age' ; const dynamicValue = 30; const dynamicObject = { name: 'Aman' , }; // Using bracket notation to //set properties dynamically dynamicObject[dynamicKey] = dynamicValue; dynamicObject[ 'city' ] = 'Noida' ; console.log(dynamicObject); |
{ name: 'Aman', age: 30, city: 'Noida' }
Approach 3: Using the spread operator
The spread operator allows merging objects into a new one with all properties copied. It creates a concise and non-destructive way to combine objects or clone them.
Syntax:
Example: in this example, we are using the above-explained approach.
Javascript
const obj1 = { name: 'Ankit' }; const obj2 = { age: 30 }; const obj3 = { city: 'Noida' }; const mergedObject = { ...obj1, ...obj2, ...obj3 }; console.log(mergedObject); |
{ name: 'Ankit', age: 30, city: 'Noida' }