使用动态键创建对象[重复]

本文翻译自:Creating object with dynamic keys [duplicate]

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

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 . 使用BabelGoogle的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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值