1674

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
  • 659
    The solution in ES6 is to put the variable in square brackets in order to evaluate it. var key = "happyCount"; myArray.push({ [key]: someValueArray });
    – Dan Cron
    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/… 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.
    – Dan Cron
    Sep 29, 2017 at 13:16
  • 3
    @Jake That is exactly what babel is for. As Dan Cron mentions above. 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.
    – Keith
    Mar 21, 2018 at 12:58

9 Answers 9

2971

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,
}
10
  • 5
    @AlexG: It was used in the question.
    – gen_Eric
    Jun 1, 2015 at 14:10
  • 405
    Note, that things changed for the better in ES6, i.e. {[key]:someValueArray}
    – Frank N
    Mar 14, 2017 at 17:53
  • 12
    @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
    Sep 28, 2017 at 5:11
  • 18
    @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. Nov 28, 2017 at 8:34
  • 32
    for those who wonder how this ES6 feature is called: it is Computed property name
    – juggernaut
    Mar 13, 2019 at 11:52
602

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
21

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

14
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
1
  • This is not a different answer than existing ones.
    – Akaisteph7
    Mar 9 at 17:37
14

In ES6 We can write objects like this

const key= "Name";
const values = "RJK"

const obj = {
    [key]: values,
}
1
  • 2
    This is not a different answer than existing ones.
    – Akaisteph7
    Mar 9 at 17:36
11

Use this.

var key = 'a'
var val = 'b'

console.log({[key]:val})

//a:'b'
2
  • 3
    This answer was already given by @kiranvj
    – Tobias S.
    Apr 14, 2022 at 9:00
  • I do like how I can get the answer very quickly, as opposed to @kiranvjs answer
    – jfunk
    Apr 15, 2022 at 14:59
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"}
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
  • This is not a different answer than existing ones.
    – Akaisteph7
    Mar 9 at 17:36
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.