-4

I have an array of objects and want to add a new object to it in a for loop. They key of the object is dynamic and inside a variable. How can I do this. My array:

var myKey = "someStringThatIsDynamic";   
var myArray[i].myKey = "myValue";
YourReflection
  • 375
  • 7
  • 22

1 Answers1

4

Just use bracket notation.

var myKey = "someStringThatIsDynamic";   
var myArray[i][myKey] = "myValue";

That allows you to assign the properties dynamically. With the other words, at runtime.

Note : Using square bracket notation allows the use of characters that can't be used with dot notation:

var foo = myForm.key[]; // incorrect syntax
var foo = myForm["key[]"]; // correct syntax
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128