tags:

views:

278

answers:

5

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 it's 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?

Thanks

+6  A: 

Yes.

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

data["PropertyD"] = 4;

// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
Georg
I didn't know you could use that syntax. I'm still a newb in JavaScript, I'm used to seeing [] used for working with arrays and wouldn't have thought to try that. Thanks!
Lee D
data.PropertyD = 4 would also work.
thedz
@thedz: data.PropertyD needs to know the property name, which isn't dynamic enough.
Georg
+1  A: 

Yes it is possible. Assuming:

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};
var propertyName = "someProperty";
var propertyValue = "someValue";

Either:

data[propertyName] = propertyValue;

or

eval("data." + propertyName + " = '" + propertyValue + "'");

The first method is preferred. eval() has the obvious security concerns if you're using values supplied by the user so don't use it if you can avoid it but it's worth knowing it exists and what it can do.

You can reference this with:

alert(data.someProperty);

or

data(data["someProperty"]);

or

alert(data[propertyName]);
cletus
Using eval is really dangerous.
Georg
Not to mention slow.
Eamon Nerbonne
A: 

You can add as many more properties as you like simply by using the dot notation:

var data = {
    var1:'somevalue'
}
data.newAttribute = 'newvalue'

or:

data[newattribute] = somevalue

for dynamic keys.

Gabriel Hurley
if the properties name is not determined until run time" - so that won't work unless you use eval, which isn't a good option
Marc Gravell
or use the [] syntax... data[somevar] = somevalue
Gabriel Hurley
A: 

Definitely. Think of it as a dictionary or associative array. You can add to it at any point.

thedz
I think we can assume an implicit "and if so, how?" in the question...
Marc Gravell
+1  A: 

Here, using your notation:

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};
var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to 
//my object?
data[propName] = 'Some New Property value'
maksymko