Square brackets:

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

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

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

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
Answer from Pointy on Stack Overflow
Top answer
1 of 2
741

Square brackets:

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

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

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

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
2 of 2
1

Associative Arrays in JavaScript don't really work the same as they do in other languages. for each statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push method:

jsArr = []; 

for (var i = 1; i <= 10; i++) { 
    jsArr.push('example ' + 1); 
} 

Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].

🌐
Medium
medium.com › analytics-vidhya › javascript-how-to-add-dynamic-key-to-object-19280ca70afd
Javascript — How to add the dynamic key to Object - Analytics Vidhya - Medium
April 5, 2023 - If you add a variable name to the Object key, It will take the variable name as the key, not the variable value. To have dynamic value as a key, use [] to add value to the object as below.
Discussions

How to type object with variable key names?
These answers are correct but there is also a shortcut syntax using a built-in utility type, Record More on reddit.com
🌐 r/typescript
8
14
March 24, 2020
TIL You can use computed property names in destructuring queries
My mind just melted. This is amazing. I can't wait to have every PR that utilizes this rejected for poor code readability. More on reddit.com
🌐 r/javascript
76
297
July 15, 2018
🌐
Codez Up
codezup.com › home › 3 ways to add dynamic key to object in javascript
3 ways to Add Dynamic Key to Object in Javascript | Codez Up
September 7, 2021 - So, 3 ways can be used to create a Dynamic key to an existing object. So, this is the way where we can add a new key to the existing object like the way we used to access the array.
🌐
ProgrammingBasic
programmingbasic.com › home › javascript › how to add dynamic key to an object in javascript
How to add dynamic Key to an object in JavaScript | ProgrammingBasic
In es6 we can directly use the variable while creating the object to set the key or property dynamically. ... FInd out how to use forEach in an object and return key, value and also convert it's properties to an array using JavaScript. ... Tutorial about the Javascript hasOwnProperty() method of an object, its use, advantages and limitations. ... Short tutorial on adding a getter to an existing JavaScript object using Object.defineProperty method.
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-set-dynamic-property-keys-to-an-object-in-javascript
How to set dynamic property keys to an object in JavaScript?
December 8, 2022 - <!DOCTYPE html> <html> <head> <title>Dynamic Property Keys - defineProperty</title> </head> <body> <h3>Setting Dynamic Property Keys using Object.defineProperty()</h3> <p id="result2"></p> <script> let Employee = { name: 'Vinay', emp_id: 101 }; let key1 = "Company"; let key2 = 'role'; Employee[key1] = 'Tutorials Point'; Object.defineProperty(Employee, key2, { value: 'Software Engineer', writable: true, enumerable: true }); document.getElementById("result2").innerHTML = 'Employee.name: ' + Employee.name + '<br/>' + 'Employee.emp_id: ' + Employee.emp_id + '<br/>' + 'Employee[key1]: ' + Employee[key1] + '<br/>' + 'Employee[key2]: ' + Employee[key2]; </script> </body> </html>
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › how-to-set-dynamic-object-properties-using-computed-property-names
How to Set Dynamic Object Properties using Computed Property Names
February 17, 2023 - But, language and isStudent are not added as static keys. They are added dynamically, as variable expressions: [key1] and [key2]. The returned values of the expressions then represent the keys that will be added to the object.
🌐
Attacomsian
attacomsian.com › blog › javascript-create-object-with-dynamic-keys
How to create an object with dynamic keys in JavaScript
March 29, 2021 - The computed property names feature allows us to assign an expression as the property name to an object within object literal notation. ... const key = 'title'; const value = 'JavaScript'; const course = { [key]: value, price: '$99' }; console.log(course.title); // JavaScript console.log(course.price); // $99 · The value of the key can be any expression as long as it is wrapped in brackets []: const key = 'title'; const value = 'JavaScript'; const course = { [key + '2']: value, price: '$99' }; console.log(course.title2); // JavaScript console.log(course.price); // $99
🌐
SamanthaMing
samanthaming.com › tidbits › 7-create-object-with-dynamic-keys
ES6 Way of Creating Object with Dynamic Keys | SamanthaMing.com
Previously, we always had to use the bracket notation to use a dynamic key. With ES6, we can finally create dynamic variable key in the object declaration.
🌐
RSWP Themes
rswpthemes.com › home › javascript tutorial › how to add key/value pair in javascript object dynamically
How To Add Key/Value Pair In Javascript Object Dynamically
March 29, 2024 - The object spread operator (...) offers a modern and efficient way to add key/value pairs to objects dynamically.
🌐
Linux Hint
linuxhint.com › dynamic-object-key-in-javascript
Linux Hint – Linux Hint
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
DEV Community
dev.to › mreigen › es6-dynamic-key-name-for-object-object-property-assignment-5a12
ES6 dynamic key (name) for object & object property assignment - DEV Community
February 4, 2021 - ES6 enables developers to create or access an object by dynamic keys or names: const key1 = "make"; const key2 = "model; const newObj = { year: 2020, [key1]: "toyota" [key2]: "prius" } You can think of many ways you can apply this to your coding scenario. How about the case where you might need to create an object with an increasing number in the key names?
🌐
Hackmamba
hackmamba.io › home › engineering › javascript dynamic object keys explained with examples
Javascript dynamic object keys explained with examples
May 26, 2026 - Before computed property names, adding a key from a variable required a two-step process. You created the object first, then assigned the dynamic key separately using bracket notation.
🌐
YouTube
youtube.com › watch
Set Dynamic Property Key in JavaScript | How to Use Dynamic Keys in JavaScript Object - YouTube
How to set dynamic property keys in JavaScript? How to use dynamic keys in javascript object? JavaScript objects have properties. Object properties have key,...
Published: January 11, 2023
🌐
C# Corner
c-sharpcorner.com › blogs › how-to-set-dynamic-javascript-object-property-keys-with-es6
How To Set Dynamic JavaScript Object Property Keys With ES6
March 16, 2021 - And in the next line we're setting a new key on this object called firstName and setting its value to harshal.
🌐
Stack Overflow
stackoverflow.com › questions › 40075390 › can-i-add-a-dynamic-key-to-an-object › 40075517
Can I add a dynamic key to an object?
function getKeyedArray(array, callback) { return array.reduce(function (r, a) { var key = callback(a); r[key] = r[key] || []; r[key].push(a); return r; }, Object.create(null)); } var fruits = [{ fruit: "apple", taste: "sour" }, { fruit: "cherry", taste: "sweet", color: "red" }]; console.log(getKeyedArray(fruits, function (i) { return i.fruit; })); console.log(getKeyedArray(fruits, function (i) { return i.taste.length; }));
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript dynamic object key
Dynamic Object Key in JavaScript | Delft Stack
March 11, 2025 - In this example, we create an empty object called person. We then define a variable dynamicKey that holds the string “favoriteColor”. Using bracket notation, we assign the value “blue” to this key in the person object.
🌐
DEV Community
dev.to › bilalmohib › how-to-create-an-object-with-dynamic-keys-in-javascript-2k35
How to create an object with dynamic keys in JavaScript? - DEV Community
December 14, 2021 - To create object with dynamic key the format is const key = "This is key" const tempObj = { ... Tagged with javascript, webdev, beginners, programming.
🌐
Abin John
abinjohn.hashnode.dev › dynamic-object-keys
Dynamic Object Keys in JavaScript
September 3, 2022 - Unlike dot notation, where what came after the dot became the final property name of the object, bracket notation offers more flexibility as we can mention expressions inside them. This makes it possible to create and access keys dynamically.