Home > Web Front-end > JS Tutorial > How Can I Dynamically Assign Keys in JavaScript Objects?

How Can I Dynamically Assign Keys in JavaScript Objects?

Linda Hamilton
Release: 2024-12-16 09:05:10
Original
810 people have browsed it

How Can I Dynamically Assign Keys in JavaScript Objects?

Dynamic Key Assignment in JavaScript Objects

When constructing JavaScript objects, assigning keys dynamically, rather than statically, can be useful. However, simply using variables as key names can lead to unexpected behavior, resulting in "key" as the property key instead.

Solution 1: Object Initialization with Brackets

To specify the object key dynamically, you need to create an empty object first, then use square brackets ([]) to set the key-value pair:

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

Solution 2: Computed Property Names (ES6)

ES6 introduced computed property names, which allow dynamic key assignment within object literal notation:

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

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

Example Fiddle:

Refer to this improved Fiddle for a practical demonstration: https://jsfiddle.net/Fr6eY/4/

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