JavaScript

Is it Possible to Add Dynamically Named Properties to JavaScript Objects?

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:

obj['propertyName'] = 'value';

 
Example

Create an object “car” with properties “color” and “model”:

var car = {
 "color": "black",
 "model": 2011
};

 
Add a property “price” dynamically using the “bracket notation”:

car["price"] = "555$";

 
Print the object on the console:

console.log(car);

 
The output indicates that the “price” property has been successfully added in the object:


Now, we will add another property in the same object:

car["name"] = "BMW";

 
Finally, print the “car” object on the console:

console.log(car);

 
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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.