Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add dynamically named properties to JavaScript object?

Tags:

javascript

In JavaScript, I've created an object like so:

var data = {     'PropertyA': 1,     'PropertyB': 2,     'PropertyC': 3 }; 

Is it possible to add further properties to this object after its initial creation if the properties name is not determined until run time? i.e.

var propName = 'Property' + someUserInput //imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to  //my object? 
like image 463
Lee D Avatar asked Jul 26 '09 09:07

Lee D


People also ask

How do you access object properties dynamically?

To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .

How do you conditionally add property to an object?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

How do you add a property to an object in JavaScript?

To add a new property to a Javascript object, define the object name followed by the dot, the name of a new property, an equals sign and the value for the new property.

How can we add or remove properties in object dynamically?

Adding/Removing Properties from an Object: For adding any property, one could either use object_name. property_name = value (or) object_name[“property_name”] = value. For deleting any property, one could easily use delete object_name. property_name (or) delete object_name[“property_name”].


1 Answers

Yes.

var data = {      'PropertyA': 1,      'PropertyB': 2,      'PropertyC': 3  };    data["PropertyD"] = 4;    // dialog box with 4 in it  alert(data.PropertyD);  alert(data["PropertyD"]);
like image 101
Georg Schölly Avatar answered Dec 18 '22 17:12

Georg Schölly