1746

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:

var key = "happyCount"; myArray.push( { key : someValueArray } ); 

but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?

Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/

9
  • 690
    The solution in ES6 is to put the variable in square brackets in order to evaluate it. var key = "happyCount"; myArray.push({ [key]: someValueArray }); Commented Apr 29, 2016 at 20:40
  • 8
    @Jake The only browser that currently does not support this es6 feature is IE11: kangax.github.io/compat-table/es6/… Commented Sep 28, 2017 at 13:47
  • 4
    @Jake That's a good point. One possible solution is to use babel to transpile ES6 into ES5. Commented Sep 29, 2017 at 13:16
  • 3
    @Jake That is exactly what babel is for. As Dan Cron mentions above. Commented Oct 2, 2017 at 15:38
  • 3
    @Jake Like Hunter says, it's best not to code for ES5 users. If you need to support older browsers, pollyfill & transpile. It's now 2018, not 2009, we really need to move on. Commented Mar 21, 2018 at 12:58

9 Answers 9

3083

You need to make the object first, then use [] to set it.

var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray.push(obj); 

UPDATE 2021:

Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.

const yourKeyVariable = "happyCount"; const someValueArray= [...]; const obj = { [yourKeyVariable]: someValueArray, } 
Sign up to request clarification or add additional context in comments.

10 Comments

@AlexG: It was used in the question.
Note, that things changed for the better in ES6, i.e. {[key]:someValueArray}
@Frank Nocke I'm looking forward to be able to use it in about 10 years time when all the 'browsers' we have to support support it...
@Jake you can program in ES6 or ES7 today, and have Babel compile your JS file back to ES5. This is how webapps are built nowadays.
for those who wonder how this ES6 feature is called: it is Computed property name
|
631

In ES6, you can do like this.

var key = "name"; var person = {[key]:"John"}; // same as var person = {"name" : "John"} console.log(person); // should print Object { name="John"} 

 var key = "name"; var person = {[key]:"John"}; console.log(person); // should print Object { name="John"}

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {}; yourObject[yourKey] = "yourValue"; console.log(yourObject ); 

example:

var person = {}; var key = "name"; person[key] /* this is same as person.name */ = "John"; console.log(person); // should print Object { name="John"} 

 var person = {}; var key = "name"; person[key] /* this is same as person.name */ = "John"; console.log(person); // should print Object { name="John"}

1 Comment

I provided a solution that I think may be of some interest to people at this link using underscore: stackoverflow.com/questions/5640988/…
29

The Reality

The problem in JS is simply that:

{ x: 2 } 

is THE SAME as:

{ "x": 2 } 

(even if you have x a variable defined!)

Solution

Add square brackets [] around the identifier of the key:

var key = "happyCount"; myArray.push( { [key] : someValueArray } );

(Nowadays the keyword var is not much used, so please use instead const or let)

tldr;

enter image description here

Comments

19

In ES6 We can write objects like this

const key= "Name"; const values = "RJK" const obj = { [key]: values, } 

2 Comments

This is not a different answer than existing ones.
Nice. No use of push.
14
var key = "happyCount"; myArray.push( { [key] : someValueArray } ); 

1 Comment

This is not a different answer than existing ones.
10

Use this.

var key = 'a' var val = 'b' console.log({[key]:val}) //a:'b' 

2 Comments

This answer was already given by @kiranvj
I do like how I can get the answer very quickly, as opposed to @kiranvjs answer
4

Given

var key = "happyCount"; const someValueArray= [1, 3, 5, 7]; 

To use key as is:

myArray.push({ [key]: someValueArray }); 

To use key with some other prefix or suffix:

myArray.push({ [`${key}Array`]: someValueArray }); 

Source: Computed property names

Comments

0

In TypeScript, it should look something like this

 let title ="Current User"; type User = { [key:string | number | symbol]: any }; let myVar: User = {}; myVar[ title ] = "App Developer"; console.log(myVar)// Prints: { Current User:"App Developer"} 

Comments

0
let key = "name"; let name= "john"; const obj ={ id:01 } obj[key] = name; console.log(obj); // output will {id:01,name:"john} 

Use square brackets shown it will set as key

1 Comment

This is not a different answer than existing ones.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.