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; }
To create dynamic keys, the square bracket notation must be used within the loop:
jsObj['key' + i] = 'example ' + 1;
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:
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:
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!' }
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!