You can use the square bracket notation to create an object with dynamic keys in JavaScript. This notation allows you to specify the property name as a string within the square brackets, which makes it possible to create object properties with dynamic names.
For example, the following code creates an object with two dynamic keys, foo
and baz
, and corresponding values of bar
and qux
:
let propertyName1 = 'foo';
let propertyValue1 = 'bar';
let propertyName2 = 'baz';
let propertyValue2 = 'qux';
let obj = {
[propertyName1]: propertyValue1,
[propertyName2]: propertyValue2
};
Code language: JavaScript (javascript)
In this code, the square bracket notation is used to set the property values of the obj
object. The property names are specified as strings within the square brackets, allowing them to be determined dynamically at runtime.
Updating an Object With Dynamic Properties
Method 1: For a Single Property
To update the property of an object using the square bracket notation in JavaScript, you can use the following syntax:
obj[propertyName] = propertyValue;
In this code, obj
is the object whose property you want to update, propertyName
is the name of the property to update, and propertyValue
is the new value you want to assign to the property.
For example, the following code updates the foo
property of the obj
object with a value of bar
:
let obj = { foo: 'baz' };
let propertyName = 'foo';
let propertyValue = 'bar';
obj[propertyName] = propertyValue;
Code language: JavaScript (javascript)
In this code, the obj
object has a foo
property with a value of baz
. The square bracket notation is then used to update the foo
property with a new value of bar
.
Method 2: For Multiple Properties
Using the object spread syntax in this way has a few advantages over using the square bracket notation to set the property value directly. For one, it allows you to add multiple properties to the object at the same time, which can be more concise and readable than setting each property individually. For example:
let obj = {};
let propertyName1 = 'foo';
let propertyValue1 = 'bar';
let propertyName2 = 'baz';
let propertyValue2 = 'qux';
obj = { ...obj, [propertyName1]: propertyValue1, [propertyName2]: propertyValue2 };
Code language: JavaScript (javascript)
In this code, the object spread syntax is used to combine the obj
object with two new properties, foo
and baz
, with corresponding values of bar
and qux
. This creates a new object that includes all of the properties from the obj
object, as well as the new foo
and baz
properties. The resulting object is then assigned to the obj
variable, replacing the original object.
Another advantage of using the object spread syntax is that it allows you to easily add properties to an existing object without mutating the original object. This is because the object spread syntax creates a new object that includes the properties from the original object, rather than modifying the original object directly.
Leave a Reply