JavaScript set object key using variable (es6 & es5)

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[key] = '+7'; // => {russia: "+7"}

Method 2:

In es6 we can direct use [ ] inside an  object

const country = "usa";
const countryCodes = {[key]:"+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.

See also  Editable HTML Table Using Javascript/Jquery With Add Edit Delete Rows

Leave a Comment