Home > Web Front-end > JS Tutorial > How Can I Create JavaScript Objects with Dynamically Assigned String Keys?

How Can I Create JavaScript Objects with Dynamically Assigned String Keys?

Mary-Kate Olsen
Release: 2024-12-06 05:07:13
Original
549 people have browsed it

How Can I Create JavaScript Objects with Dynamically Assigned String Keys?

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

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

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

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

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!

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