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
Community
  • 1
  • 1
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

2 Answers2

4

Use square bracket notation:

obj[propertyName] = something;
VisioN
  • 143,310
  • 32
  • 282
  • 281
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.

David G
  • 94,763
  • 41
  • 167
  • 253