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?
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] .
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.
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.
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”].
Yes.
var data = { 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 }; data["PropertyD"] = 4; // dialog box with 4 in it alert(data.PropertyD); alert(data["PropertyD"]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With