本文翻译自:Creating object with dynamic keys [duplicate]
First off, I'm using Cheerio for some DOM access and parsing with Node.js. 首先,我使用Cheerio进行一些DOM访问,并使用Node.js进行解析。 Good times. 美好的时光。
Heres the situation: 情况如下:
I have a function that I need to create an object. 我具有创建对象所需的功能。 That object uses variables for both its keys and values, and then return that single object. 该对象为其键和值使用变量,然后返回该单个对象。 Example: 例:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value');
return { key : value }
})
callback(null, inputs);
}
It outputs this: 它输出:
[ { key: '1' }, { key: '1' } ]
( .map()
returns an array of objects fyi) ( .map()
返回对象数组fyi)
I need key
to actually be the string from this.attr('name')
. 我需要key
实际上是this.attr('name')
的字符串。
Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do? 考虑到我要做什么,在Java中将字符串分配为键的最佳方法是什么?
#1楼
参考:https://stackoom.com/question/1LEkO/使用动态键创建对象-重复
#2楼
You can't define an object literal with a dynamic key. 您不能使用动态键定义对象文字。 Do this : 做这个 :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer). 没有捷径(编辑:ES6现在有一个捷径,请参见另一个答案)。
#3楼
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys : Object Initializer spec . 在JavaScript的新ES2015标准 (以前称为ES6)中,可以使用计算键创建对象 : Object Initializer spec 。
The syntax is: 语法为:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into: 如果应用于OP的场景,它将变成:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity . 注意: 浏览器兼容性仍然需要编译器 。
Using Babel or Google's traceur , it is possible to use this syntax today . 使用Babel或Google的traceur , 今天可以使用此语法 。
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string. 在早期的JavaScript规范(ES5及更低版本)中,对象文字中的键始终按字面意义解释为字符串。
To use a "dynamic" key, you have to use bracket notation : 要使用“动态”键,必须使用方括号表示法 :
var obj = {};
obj[myKey] = value;
In your case: 在您的情况下:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}