Skip to content

JavaScript dynamic object key | Example code

  • by

Use Square brackets notation to create dynamic object key in JavaScript. If you want multiple dynamic keys and values use [ ] operator with a for loop iterating through some value.

jsObj['key'] = 'value';

JavaScript dynamic object key

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
   jsObj = {};

   for (var i = 1; i <= 5; i++) {
    jsObj['key' + i] = 'value' + 1;
   }

   console.log(jsObj)
 </script>

</body>
</html> 

Output:

JavaScript dynamic object key

JavaScript set object key by variable

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

You can also use dynamic keys when accessing object properties. For example:

const myObj = {
  myKey: 'myValue'
};

const dynamicKey = 'myKey';
console.log(myObj[dynamicKey]); // outputs 'myValue'

Comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *