Home  >  Article  >  Web Front-end  >  How to Dynamically Set Keys in JavaScript Objects?

How to Dynamically Set Keys in JavaScript Objects?

Susan Sarandon
Susan SarandonOriginal
2024-11-05 08:10:02776browse

How to Dynamically Set Keys in JavaScript Objects?

How to Create a Dynamic Key for a JavaScript Object Variable

When attempting to create a dynamic key for a JavaScript object, using this syntax

jsObj{'key'   i} = 'example'   1;
will not work. The correct approach employs square brackets:

<code class="js">jsObj['key' + i] = 'example' + 1;</code>

In JavaScript, arrays are a specialized type of object, with the distinction being that they maintain a length property that reflects the count of numeric properties (indices) plus one. This special behavior is not mimicked by standard objects, but the square bracket operator works identically on both types.

For setting a property with a numeric key on an array instance, the length property will be automatically updated to reflect the largest numeric key. However, for a plain object, no such update occurs.

It's important to note that serializing an array instance to JSON only includes the numerically-named properties, excluding any others.

In ES6, you can use Computed Property Names for a more concise syntax:

<code class="js">var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };</code>

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