JavaScript set object key by variable

Javascript

Javascript Problem Overview


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/

Javascript Solutions


Solution 1 - Javascript

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,
}

Solution 2 - Javascript

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"}

Solution 3 - Javascript

Use this.

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

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

//a:'b'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHunter McMillenView Question on Stackoverflow
Solution 1 - Javascriptgen_EricView Answer on Stackoverflow
Solution 2 - JavascriptkiranvjView Answer on Stackoverflow
Solution 3 - JavascriptdevtunusView Answer on Stackoverflow