Creating a JavaScript Object with a Dynamic Property Name


After going crazy trying to dynamically push objects into an JavaScript array I hit another wall. Dynamic object property names. For example, how do you dynamically write myObject.dynamicName?

Well, after much googling I remembered that magical function eval(). The best way, so far, to write dynamic property names is to parse,eval(), a string name into the property definition. For example:

myObject = [];
propertyName="crazyHorse";
propertyValue="David"; 
eval("myObject."+propertyName+"='"+propertyValue+"'");
alert(myObject.crazyHorse);
// Alerts "David"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s