How to add dynamic Key to an object in JavaScript

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' }
Scroll to Top