Home >Web Front-end >JS Tutorial >How Can I Create JavaScript Objects with Dynamic Keys from Variables?

How Can I Create JavaScript Objects with Dynamic Keys from Variables?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 10:45:12890browse

How Can I Create JavaScript Objects with Dynamic Keys from Variables?

Creating Objects with Dynamic Keys

For accessing and parsing DOM elements in Node.js, Cheerio is commonly used. The question arises regarding how to dynamically create an object with both keys and values derived from variables.

Traditionally, in JavaScript (pre-ES6), creating objects with dynamic keys required bracket notation:

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

In the provided scenario, this can be implemented as:

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

However, with the advent of ES6, computed keys can be used in object initializers, offering a more concise syntax:

var obj = {
  [myKey]: value,
}

Applying this to the problem at hand yields:

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

  callback(null, inputs);
}

Note that using computed keys requires a transpiler such as Babel or Google's Traceur for browser compatibility.

The above is the detailed content of How Can I Create JavaScript Objects with Dynamic Keys from Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn