javascript 使用动态键创建对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19837916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:59:35  来源:igfitidea点击:

Creating object with dynamic keys

javascriptobject

提问by JDillon522

First off, I'm using Cheeriofor some DOM access and parsing with Node.js. Good times.

首先,我使用Cheerio进行一些 DOM 访问并使用 Node.js 进行解析。美好时光。

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()返回对象数组仅供参考)

I need keyto 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?

考虑到我要做什么,在 Javascript 中将字符串分配为键的最佳方法是什么?

回答by Renato Zannon

In the new ES2015 standardfor JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.

在JavaScript的新ES2015 标准(以前称为 ES6)中,可以使用计算键创建对象对象初始化规范

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

回答by Denys Séguret

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,请参阅另一个答案)。