Dynamic object property names in Javascript

Have ever needed to create a Javascript object with dynamic property names? You may have found that your dynamic variable name was actually used literally. eval() is your friend…

// Initialise an object.
var myObj = new Object();

var testValue = 'Jim Lam'; 

// Assign your dynamic property name. e.g. via PHP.
var dynamicPropertyName = 'changeable'; 

// WRONG. Creates a property called 'dynamicPropertyName'.
myObj.dynamicPropertyName = testValue;

// RIGHT. Creates a property called 'changeable'.
eval("myObj." + dynamicPropertyName + " = '" + testValue + "' ");

// Check.
alert(myObj.changeable); // Jim Lam


If you found this article useful, help me out by leaving a comment below and clicking the Like button.

This entry was posted in Javascript. Bookmark the permalink.

Comments are closed.