"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Dynamically Set Keys in JavaScript Objects?

How to Dynamically Set Keys in JavaScript Objects?

Published on 2024-11-14
Browse:535

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 <pre>jsObj{'key' + i} = 'example' + 1;</pre> will not work. The correct approach employs square brackets:

jsObj['key' + i] = 'example' + 1;

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:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3