7

I have a javascript array and a variable. I want to push onto the array an object with the variable as the property name, but it must hold the value of the variable, not the variable as a string. If I have this code:

array = [];
var x = 10;
array.push({x: y});

The x is stored as a string "x", not a variable that contains the value of var x. Any help is appreciated.

Ben
  • 2,962
  • 2
  • 20
  • 26

1 Answers1

16

The property name in an object literal is not evaluated as a variable. You have to assign the property using bracket notation.

var obj = {};
obj[x] = y;
array.push(obj);
Barmar
  • 741,623
  • 53
  • 500
  • 612