1643

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/

t.niese
  • 39,256
  • 9
  • 74
  • 101
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • 648
    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 '16 at 20:40
  • @DanCron Sounds great, but when will 99%+ of 'browsers' in the user base be ES6-capable? – Jake Sep 28 '17 at 07:09
  • 8
    @Jake The only browser that currently does not support this es6 feature is IE11: https://kangax.github.io/compat-table/es6/#test-object_literal_extensions_computed_properties – Hunter McMillen Sep 28 '17 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 '17 at 13:16
  • @HunterMcMillen You can't normally assume everyone is using the latest version of whatever browser - a significant number of web users have a significantly out of date browser. Your use of ES6-specific constructs will break your site for them. – Jake Sep 30 '17 at 01:47
  • 3
    @Jake That is exactly what babel is for. As Dan Cron mentions above. – Hunter McMillen Oct 02 '17 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 '18 at 12:58
  • In my case, Dan Cron's tip was fastest to correct my code. As to what Keith says, I definitely agree. As to what @Hunter McMillen said about IE11, I am wondering more generally: Is it reasonable to take into account Microsoft browsers now, since their world market share amounts to peanuts nowadays? Just as Firefox (my favourite one), they are bound to die presently, including Opera. Quoting Keith: ' let's move on'. – Brice C. Apr 02 '22 at 09:32
  • Does this answer your question? [How to use a variable for a key in a JavaScript object literal?](/q/2274242/90527) – outis Sep 01 '22 at 07:52

8 Answers8

2941

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,
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
592

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"}
kiranvj
  • 32,342
  • 7
  • 71
  • 76
  • I provided a solution that I think may be of some interest to people at this link using underscore: http://stackoverflow.com/questions/5640988/how-do-i-interpolate-a-variable-as-a-key-in-a-javascript-object/30608422#30608422 – rashadb Jun 02 '15 at 23:46
14
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Ishaan Kapoor
  • 334
  • 2
  • 6
  • 1
    Please read [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others. – Saeed Zhiany Jul 26 '22 at 03:16
  • This is not a different answer than existing ones. – Akaisteph7 Mar 09 '23 at 17:37
14

In ES6 We can write objects like this

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

const obj = {
    [key]: values,
}
Rahul Pawar
  • 157
  • 1
  • 3
14

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

underflow
  • 1,545
  • 1
  • 5
  • 19
11

Use this.

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

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

//a:'b'
devtunus
  • 121
  • 1
  • 2
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"}
jbz
  • 3
  • 3
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