Utilizing Dynamic Properties in Objects
Creating objects with variable properties in JavaScript can occasionally present challenges. In this context, we'll delve into the techniques to assign strings as object keys, providing solutions for both the latest ES2015 standard and earlier JavaScript versions.
ES2015 (ES6) Solution
1. Computed Properties:
ES2015 introduces the concept of computed properties, enabling the creation of objects with keys that are dynamically computed:
var obj = { [myKey]: value, };
Applying this to the scenario:
stuff = function (thing, callback) { var inputs = $('div.quantity > input').map(function () { return { [this.attr('name')]: this.attr('value'), }; }); callback(null, inputs); };
Note: For browser compatibility, consider using a transpiler such as Babel.
Pre-ES2015 Solution
2. Bracket Notation:
ES5 and earlier versions require the use of bracket notation to assign dynamic keys:
var obj = {}; obj[myKey] = value;
In this instance:
stuff = function (thing, callback) { var inputs = $('div.quantity > input').map(function () { var key = this.attr('name'); var value = this.attr('value'); var ret = {}; ret[key] = value; return ret; }); callback(null, inputs); };
The above is the detailed content of How Can I Create JavaScript Objects with Dynamically Assigned String Keys?. For more information, please follow other related articles on the PHP Chinese website!