JavaScript

Dynamic Object Key in JavaScript

An object is an entity that stores data in key-value pairs. In JavaScript, object keys and values can be created multiple ways, including assignment using dot or bracket notation or object literals during initialization. But sometimes an object key needs to be added dynamically.

This blog post will define the dynamic object key in JavaScript.

How to Set Dynamic Object Key in JavaScript?

In the ES6 version of JavaScript, developers can dynamically set the JavaScript property keys for their objects using the Bracket notation.

Syntax:

Follow the given syntax for setting a dynamic object key in JavaScript with bracket notation:

[keyVar] = keyName;

In the given syntax:

  • keyVar” is the variable name that stores the name of the key that will be added dynamically in the object.
  • keyName” is the name of a key that will be set dynamically in an object.

Example 1:

First, create a variable “newKey” for storing the name of the key “skill”:

var newKey = 'skill';

Then, create an object “info”, with properties “name”, “age”, and “email”. Add another attribute of an object using the key “skill” that will dynamically add in an object:

var info = {

    name: 'John',

    age: 28,

    email: '[email protected]',

    [newKey]: 'JavaScript'

};

Call the “console.log()” method by passing an object as an argument for printing all the properties of the object in a key-value pair:

console.log(info);

Output

The above output shows that the dynamic key “skill” is successfully added and accessed in an object:

Example 2:

Let’s print the value of the key “skill” stored in the “info” object:

console.log(info.skill);

Output

The output indicates that the object “info” successfully accesses the value of the “newKey” variable and stores it as a dynamic key.

Conclusion

For adding an object key dynamically, use the bracket notation. First, store the key in a variable and then specify the variable name in bracket notation to set a key with value as a key-value pair in an object. This blog post defines the dynamic object key in JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.