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

查看:31
本文介绍了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);


2021 年更新:


UPDATE 2021:

计算属性名称功能是在 ECMAScript 2015 (ES6) 中引入的,它允许您以 JavaScript 对象文字表示法动态计算对象属性的名称.

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

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

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