Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

javascript - 使用动态键创建对象[重复](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中将字符串分配为键的最佳方法是什么?)

  ask by JDillon522 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...