How to add dynamic Key to an object in JavaScript
Short tutorial on how to create and add dynamic key to an object in JavaScript using bracket syntax and ES6 methods.
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.
- Using bracket syntax
- 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
Use Array forEach() to loop through JavaScript object
FInd out how to use forEach in an object and return key, value and also convert it's properties to an array using JavaScript.
JavaScript hasOwnProperty() method of an Object
Tutorial about the Javascript hasOwnProperty() method of an object, its use, advantages and limitations.
How to add getter to an existing JavaScript Object
Short tutorial on adding a getter to an existing JavaScript object using Object.defineProperty method.
How to remove a property from an object in JavaScript?
This article is about how to remove a property from an object in javascript using delete operator.
