Home >Web Front-end >JS Tutorial >How to Access JavaScript Object Keys Using Variables?

How to Access JavaScript Object Keys Using Variables?

DDD
DDDOriginal
2024-12-28 03:14:10976browse

How to Access JavaScript Object Keys Using Variables?

Accessing JavaScript Object Keys Via Variables

When building objects in JavaScript and storing keys in variables, you may encounter a situation where the object keys are set to the variable name ("key" in this case) instead of the variable's value.

Solution:

To resolve this issue, you can create the object first and then use square brackets ([]) to set the key dynamically from the variable:

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

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

This method allows you to set the object key using the value stored in the variable.

ES6 Update (2021):

ES6 introduced computed property names, which provide a more concise syntax for dynamically setting object keys:

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

const obj = {
    [yourKeyVariable]: someValueArray,
}

By using square brackets within object literals, you can now set object keys based on the value of variables, making your code more flexible and readable.

The above is the detailed content of How to Access JavaScript Object Keys Using Variables?. 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