JavaScript通过变量设置对象键[重复]

本文翻译自:JavaScript set object key by variable [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 5 years ago . 5年前关闭。

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: 我正在用JavaScript构建一些对象并将这些对象推入数组,将要使用的键存储在变量中,然后像下面这样创建对象:

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. 但是,当我尝试检查每个对象的对象数组时,键是"key"而不是变量键的值。 Is there any way to set the value of the key from a variable? 有什么方法可以通过变量设置键的值吗?

Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/ 小提琴以获得更好的解释: http : //jsfiddle.net/Fr6eY/3/


#1楼

参考:https://stackoom.com/question/mHsN/JavaScript通过变量设置对象键-重复


#2楼

You need to make the object first, then use [] to set it. 您需要先创建对象,然后使用[]进行设置。

var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2018: 更新2018:

If you're able to use ES6 and Babel, you can use this new feature: 如果您能够使用ES6和Babel,则可以使用此新功能:

{
    [yourKeyVariable]: someValueArray,
}  

#3楼

Try something like this (check ES6 example at the end of answer) 尝试这样的事情(在答案末尾查看ES6示例)

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

In ES6, you can do like this. 在ES6中,您可以这样做。

var key = "name";
var person = {[key]:"John"};
console.log(person); // should print  Object { name="John"}

  var key = "name"; var person = {[key]:"John"}; console.log(person); // should print Object { name="John"} 

发布了0 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/p15097962069/article/details/105390055