Home > Web Front-end > JS Tutorial > How Can I Dynamically Set Object Keys Using Variables in JavaScript?

How Can I Dynamically Set Object Keys Using Variables in JavaScript?

Barbara Streisand
Release: 2025-01-04 17:48:13
Original
522 people have browsed it

How Can I Dynamically Set Object Keys Using Variables in JavaScript?

Setting Object Keys Using Variables in JavaScript

In JavaScript, when constructing objects, you may encounter a situation where you want to dynamically set the key's value using a variable. However, by simply following common object initialization syntax, you will observe that the key is set to the variable's name rather than the intended value.

Problem Description

The following code snippet illustrates the issue:

var key = "happyCount";
myArray.push({ key: someValueArray });
Copy after login

Inspecting myArray after this operation reveals that the key for each object is "key" instead of the intended value stored in the key variable.

Solution: Creating the Object First

To resolve this issue, create the object before setting the key using the bracket notation []. This syntax allows you to dynamically set the key's value from a variable.

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);
Copy after login

Now, the created object will have the key set to the value of the key variable.

ECMAScript 2015 Computed Property Names

ECMAScript 2015 (ES6) introduced computed property names, a feature that allows for even more flexibility in defining object keys dynamically. This syntax uses square brackets [] to enclose the property name, which can be any valid JavaScript expression.

const yourKeyVariable = "happyCount";
const someValueArray = [...];

const obj = {
    [yourKeyVariable]: someValueArray,
};
Copy after login

This code achieves the same result as the previous solution but uses the computed property names syntax, which is more concise and expressive.

The above is the detailed content of How Can I Dynamically Set Object Keys Using Variables in JavaScript?. 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