javascript - Adding Attributes to JS Object Literal with a Function -


i trying add "attribute" : "value", js object using function, having trouble. i'm hoping of might able help.

allow me create context...

here object resides in file "myobject.js":

var myobject = { '12-25-2012' = '<p>christmas</p>',  '07-18-2013' = '<p>my birthday</p>'  }; 

now i've got more information want add object. know can inserting following in script tags or in myobject.js file below object this:

var thedate = '07-23-2013';  myobject[thedate] = "<p>mom's birthday</p>"; 

but that's not how want happen. want add exact same information, sake of context, function let's name myfunction(). reason being, in application, want able pass parameters function define object's new attribute's , values.

this tried, isn't working:

function myfunction(){ var thedate = '07-23-2013';  myobject[thedate] = "<p>mom's birthday</p>"; } 

any thoughts going wrong? appreciated!!

i discourage using brackets [] on object type variables.

also, must define attributes/properties in object using attribute : value notation, there no equal sign used.

you can achieve want using object.defineproperty(mdn) method:

javascript

var myobject = {     '12-25-2012': '<p>christmas</p>',     '07-18-2013': '<p>my birthday</p>' };   function myfunction(attribute,value) {     object.defineproperty(myobject, attribute, {         value: value,         /* lets overwrite value later */         writable: true,         /* lets see attribute in object attributes/properties list , in length */         enumerable: true,     });     return myobject; }  /* displaying content of object */ console.dir(myfunction("07-23-2013","<p>mom's birthday</p>")); alert(json.stringify(myobject,null,4)); 

so call function way : myfunction(thedate, thevalue);

live demo


Comments