How to create an object property from a variable value in JavaScript?

ecu picture ecu · Feb 11, 2010 · Viewed 369.6k times · Source

I want to add a new property to 'myObj', name it 'string1' and give it a value of 'string2', but when I do it it returns 'undefined:

var myObj = new Object;
var a = 'string1';
var b = 'string2';
myObj.a = b;

alert(myObj.string1); //Returns 'undefined'
alert(myObj.a); //Returns 'string2'

In other words: How do I create an object property and give it the name stored in the variable, but not the name of the variable itself?

Answer

philfreo picture philfreo · Feb 11, 2010