patternjavascriptCritical
Is it possible to add dynamically named properties to JavaScript object?
Viewed 0 times
possibleobjectpropertiesdynamicallyaddnamedjavascript
Problem
In JavaScript, I've created an object like so:
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 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?Solution
Yes.
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);Context
Stack Overflow Q#1184123, score: 1522
Revisions (0)
No revisions yet.