JavaScript set object key via variable
P粉106301763
P粉106301763 2023-10-09 12:00:10
0
2
569

I am building some objects in JavaScript and pushing these objects into an array, I store the key I want to use in a variable and then create my object like this:

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

But when I try to check the object array for each object, the key is "key" instead of the value of the variable key. Is there any way to set the value of a key from a variable?

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

P粉106301763
P粉106301763

reply all(2)
P粉321676640

In ES6, you can do 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 name is Computed property name, it is implemented using bracket notation (square brackets) []

Example: { [variableName] : someValue }

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"}
P粉579008412

You need to create the object first and then set it using [].

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);

2021 Update:

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

const yourKeyVariable = "happyCount";
const someValueArray= [...];

const obj = {
    [yourKeyVariable]: someValueArray,
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template