Creating a javascript object with dynamic property name
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   amit_gupta
Posted On:   Friday, March 7, 2008 07:51 AM

Hello All, Please consider the following code: var myobj=new Object(); myobj.name="Amit"; myobj.dob="1990"; later on whenever i require, i can simply refer to myobj.name or myobj.dob. Now the question is : what if i want to create an object whose property name (such as name and dob in the example) is dynamic. Consider following snippet: var myproperty="name"; myobj.myproperty="Amit"; will create an object property ( propertyname== myproperty) but i intended it to be "name". How can i do that ..   More>>


Hello All,

Please consider the following code:

var myobj=new Object();

myobj.name="Amit";

myobj.dob="1990";



later on whenever i require, i can simply refer to myobj.name or myobj.dob.


Now the question is :

what if i want to create an object whose property name (such as name and dob in the example) is dynamic.



Consider following snippet:


var myproperty="name";



myobj.myproperty="Amit";


will create an object property ( propertyname== myproperty) but i intended it to be "name".





How can i do that ...

Please help...



Thanking you

   <<Less

Re: Creating a javascript object with dynamic property name

Posted By:   Anonymous  
Posted On:   Tuesday, April 15, 2008 06:04 AM

srdydty

Re: Creating a javascript object with dynamic property name

Posted By:   Firat_Tiryaki  
Posted On:   Tuesday, March 11, 2008 04:04 AM

You should use eval function for that.


Check out the below lines, sure it will help;



x=new Object();

propertyName="nameProperty";

propertyValue="John";

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

alert(x.nameProperty);

About | Sitemap | Contact