使用动态键创建对象 [英] Creating object with dynamic keys

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

问题描述

首先,我正在使用 Cheerio 进行DOM访问和使用Node.js进行解析。好时光。

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

下面是这种情况:

我有一个创建对象所需的功能。该对象使用其键和值的变量,然后返回该单个对象。示例:

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

它输出:

[ { key: '1' }, { key: '1' } ]

.map()返回一个对象数组fyi)

(.map() returns an array of objects fyi)

我需要 key 实际上是来自 this.attr('name')的字符串。

I need key to actually be the string from this.attr('name').

考虑到我正在尝试做什么,最好的方法是将字符串指定为Javascript中的键?

Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?

推荐答案

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

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

语法为:

var obj = {
  [myKey]: value,
}

如果应用于OP的场景,它会变成:

If applied to the OP's scenario, it would turn into:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    return {
      [this.attr('name')]: this.attr('value'),
    };
  }) 

  callback(null, inputs);
}

注意: <仍然需要转发器< a href =https://kangax.github.io/compat-table/es6/>浏览器兼容性。

使用 Babel Google的跟踪,可以立即使用此语法

在早期的JavaScript规范(ES5及以下版本)中,对象文字中的键始终按字面解释为字符串。

In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.

要使用动态键,您必须使用 括号表示法

To use a "dynamic" key, you have to use bracket notation:

var obj = {};
obj[myKey] = value;

在您的情况下:

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

这篇关于使用动态键创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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