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粉3216766402023-10-10 10:06:39
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粉5790084122023-10-10 00:58:48
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, }