How to add dynamic Key to an object in JavaScript

featured Image

In this article, we will learn how to add keys dynamically in objects in JavaScript.

If you are working on a project and have to insert a key / property (which is fetch from a rest API ) to an existing JavaScript Object, then you can follow the steps in this article.

What is a JavaScript object?

Javascript objects are entities with property and data types. The properties are collections of key-value pairs. In a Javascript object, a key can also have a method as a value.

const obj = {
    key1 = value,
    key2 = value
}

To access any key / property in JavaSript we can do this.

const accessVal = obj[key2]

This will return us the value of key2.

Add key dynamically in Javascript object

To add a key to our object we can use any of the two methods.

  1. Using bracket syntax
  2. Using ES6 method

Using bracket syntax to add dynamic key

This is a very simple way to add a key to your JavaScript object. We have to create the key using a bracket and assign a value to it.

Example:

const key = 'color';

const objCar = {
    name: 'Tesla'
} 

objCar[key] = 'red'

console.log(objCar)

Output:

{ name: 'Tesla', color: 'red' }

As you can see we have added the key(color) with value (red) in our object (objCar).

Using the modern ES6 method

In the first method, first, the object is created, and then using the square bracket accessor we have added the new key / property to it. We cannot pass the dynamic key while creating the object.

However, this problem gets solved in the ES6 method.

In es6 we can directly use the variable while creating the object to set the key or property dynamically.

Example:

const key = 'color';

const objCar = {
    name: 'Tesla'
    [key]: 'red'
} 

console.log(objCar)

Output:

{ name: 'Tesla', color: 'red' }

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more