Home > Web Front-end > JS Tutorial > body text

How to Create Dynamic Keys in JavaScript Objects?

Susan Sarandon
Release: 2024-11-06 09:47:03
Original
970 people have browsed it

How to Create Dynamic Keys in JavaScript Objects?

Creating Dynamic Keys in JavaScript Objects

In an attempt to add keys dynamically to an object, the following approach may not achieve the desired result:

jsObj = {};

for (let i = 1; i <= 10; i++) {
    jsObj{'key' + i} = 'example ' + 1;
}
Copy after login

To create dynamic keys, the square bracket notation must be used within the loop:

jsObj['key' + i] = 'example ' + 1;
Copy after login

Understanding Object Properties and Array Behavior

JavaScript objects can have property names that are numeric strings (e.g., "0", "5", "207"). However, the behavior of array instances differs significantly:

  • Arrays maintain a length property indicating the number of numeric property names plus one.
  • Setting the length property removes numeric property names.

This behavior has no impact on the functioning of the square bracket operator, which provides access and modification of object properties.

Setting Properties with Numeric Names

When setting properties with numeric names using the square bracket notation, the following occurs:

  • In an array instance, the length property is updated if the numeric name is the largest existing one.
  • In a plain object, no such side-effect occurs.

Therefore, using arrays to store numeric properties may be beneficial when maintaining the length property is desired.

JSON Serialization Considerations

When working with JSON serialization, it's important to be aware that only numerically named properties of arrays are included in the serialized form. Any other properties added will be lost.

ES2015 Computed Property Names

In ES6 JavaScript, computed property names can be easily used to handle dynamic keys:

let key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// { 'DYNAMIC_KEY': 'ES6!' }
Copy after login

The above is the detailed content of How to Create Dynamic 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!