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

How Can I Create JavaScript Objects with Dynamic Keys?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 22:05:17188browse

How Can I Create JavaScript Objects with Dynamic Keys?

Creating Objects with Dynamic Keys

In JavaScript, the keys in an object literal are typically static strings. However, there are times when you may need to dynamically assign keys to objects based on input data.

In this scenario, the user has a function that needs to create an object with keys and values that are dynamically determined. However, simply using the .map function results in an array of objects with the same key name.

Solution 1: Computed Keys (ES2015)

In the recently introduced ES2015 standard, objects can be created with computed keys. Using this syntax, the key in an object literal can be specified dynamically as a variable or expression.

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

  callback(null, inputs);
};

Solution 2: Bracket Notation (ES5 and Below)

In earlier versions of JavaScript (ES5 and below), dynamic keys can be assigned using bracket notation. This involves defining the key as a string within square brackets.

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

By using either of these techniques, you can dynamically create object keys based on input data in JavaScript, ensuring that the keys match the desired values.

The above is the detailed content of How Can I Create JavaScript Objects with Dynamic Keys?. 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