JavaScript按变量设置对象键 [英] JavaScript set object key by variable

查看:98
本文介绍了JavaScript按变量设置对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用JavaScript构建一些对象并将这些对象推送到一个数组中,我正在存储我想要在变量中使用的键,然后像这样创建我的对象:

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 } );

但是当我尝试检查每个对象的对象数组时,键是key而不是变量键的值。有没有办法从变量设置键的值?

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?

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

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

推荐答案

您需要先创建对象,然后使用 [] 设置它。

You need to make the object first, then use [] to set it.

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

更新2018年:

如果你'我可以使用这个新功能:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  

这篇关于JavaScript按变量设置对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆