While working with JavaScript, programmers frequently need to add dynamic properties in an object, such as a form where users can add items with dynamically named properties. In some cases, it is required to organize data into objects, with the features of these objects requiring dynamic naming dependent on the data they are interacting with. In general, dynamically named properties can be useful whenever you need to build an object with properties that are not known until runtime.
This tutorial will define whether it is possible to add named properties dynamically in objects in JavaScript.
Is It Possible/Feasible to Add/Insert Dynamically Named Properties to Objects in JavaScript?
Yes, dynamically named properties can be added to JavaScript objects. For this purpose, utilize the “square bracket notation”.
Syntax
Follow the given mentioned syntax for adding named properties dynamically into the objects:
Example
Create an object “car” with properties “color” and “model”:
"color": "black",
"model": 2011
};
Add a property “price” dynamically using the “bracket notation”:
Print the object on the console:
The output indicates that the “price” property has been successfully added in the object:
Now, we will add another property in the same object:
Finally, print the “car” object on the console:
Output
We have compiled all the essential information relevant to adding named properties dynamically in the object.
Conclusion
In JavaScript, you can add properties to an object dynamically using the “square bracket notation” by using the following syntax “obj[‘propertyName’] = ‘value’”. In this tutorial, we defined the concept of whether it is possible to add named properties dynamically in objects in JavaScript.