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.

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

With ES6, this can be done more succinctly {[x]: y}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.