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!