How To Set Dynamic JavaScript Object Property Keys With ES6

Introduction

 
The es6 version of JavaScript has introduced a large variety of features that have made a huge impact on the way people write JavaScript code. In this article, we'll take a look at a new feature that came along with es6 that enables the developers to dynamically set the property keys for their objects in JavaScript.
 

Before ES6

 
Before the rise of es6, there were primarily two ways to set object keys.
  1. Using the dot accessor
  2. And using the square bracket accessor.

Using the dot accessor

 
The dot accessor is one of the most common ways of accessing the values from or set values into the object. The syntax to set object property using dot accessor is as follows,
  1. objectName.propertyKey = propertyValue;
Let's understand this in detail using an example,
  1. const user = {};
  2. user.firstName = 'Harshal';
In the above code snippet, we're first creating an object with the name user and setting its value to an object literal. And in the next line we're setting a new key on this object called firstName and setting its value to harshal.
 
The problem with the above approach is we cannot set the object keys dynamically. For example, we cannot hold the key name firstName inside a variable and then use that variable to set the key-value pair.
 

Using the square bracket accessor

 
The syntax to set object value using the square bracket accessor is as follows,
  1. objectName['propertyName'] = propertyValue;
Lets take a look at an example,
  1. const user = {};
  2. user['firstName'] = 'Harshal';
In the above code snippet, we're setting the value for property firstName to harshal. And unlike dot accessor it allows us to set property keys dynamically.
  1. const user = {};
  2. const key = 'firstName'
  3. user[key] = 'Harshal';
  4. console.log(user);
  5. // Output: {firstName: "Harshal"}
But prior to es6, it was not possible to set the keys dynamically while creating the object. (As you can see in the above code we're setting the key after we've created the object)
 
The es6 version of JavaScript comes bundled with a solution to this problem. Now, we can use variables while creating the object to dynamically set the property.
  1. let key = 'firstName';
  2. const user = {
  3.    [key]: 'Harshal'
  4. };
  5. console.log(user);
  6. // {firstName: "Harshal"}
As you can see in the above code snippet, we're setting the property using the key variable.
 
That's it.
 
I hope you enjoyed this article. In case you've any feedback or queries please do let me know in the comment section.