3

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

I want to create an object using a value in a variable as the property name.

I have a variable called propertyName:

propertyName = "first";

How do I use the value stored in this variable as object property, as in the following?

obj.first = something; // 'first' should be extracted from propertyName
0

2 Answers 2

4

Use square bracket notation:

obj[propertyName] = something;
3

This should work:

object[ propertyName ];

It's an alternative form to the dot notation. What sets it apart from it is that it allows you to dynamically generate the property name using strings.

Not the answer you're looking for? Browse other questions tagged or ask your own question.