JavaScript set object key using variable (es6 & es5)

javascript images
Written by Vithal Reddy

Sometimes you want assign key to your js object, that key is dynamic, coming from database or user input etc, you can’t define it as normal object key, for doing this we will see multiple methods including new es6 method on how to use a variable as an object property or key in javascript

Let us consider the following object:

const countryCodes = {


In the above object, if you want to add another country code that coming from another variable instead of a direct key, then you can’t directly give a variable name in key, instead, you have to use one of the following methods.

Method 1:

we will create an object first and then we will use   to add a dynamic key or property to javascript object

const country = "russia";
const countryCodes = {};
countryCodes = '+7'; // => {russia: "+7"}

Method 2:

In es6 we can direct use  inside an  object

const country = "usa";
const countryCodes = {:"+1"};
console.log(countryCodes); => {usa:"+1"}

Method 2 should be used in most cases as it gives clean syntax and method 1 should only be used in case of no es6 support.

Javascript can trickier sometimes, but if you know a few tricks, Then you can easily conquer javascript. Now you know how to set an object key using a variable in javascript.

About the author

Vithal Reddy

Vithal Reddy is a seasoned technology professional with expertise in Full Stack Web development, Micro services and Scaling infrastructure on Cloud.
More at