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
Release: 2024-12-08 10:45:12
Original
835 people have browsed it

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;
Copy after login

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);
}
Copy after login

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

var obj = {
  [myKey]: value,
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template