Get an Object's Value by Variable Key in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20212 min read

banner

Photo by Spencer Pugh

Get an Object's Value by Variable Key #

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar]. The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back.

index.js
const obj = { country: 'Chile', name: 'Tom', }; // โœ… Get object value by variable key const myVar = 'country'; console.log(obj[myVar]); // ๐Ÿ‘‰๏ธ "Chile" // โœ… Set object key by variable const num = 4; obj['myKey' + num] = 'someValue'; console.log(obj.myKey4); // ๐Ÿ‘‰๏ธ "someValue"

We can access an object's properties using:

  • bracket notation
  • dot notation
index.js
const obj = { country: 'Chile', name: 'Tom', }; // โœ… Using bracket notation with string console.log(obj['name']); // ๐Ÿ‘‰๏ธ "Tom" // โœ… Using dot notation console.log(obj.name); // ๐Ÿ‘‰๏ธ "Tom"
When a variable has to be evaluated to a specific key, you have to use the bracket [] notation syntax.

We used bracket notation to evaluate a myVar variable and access the key country on the object.

The variable or expression we passed to the brackets gets evaluated before accessing the object at the specific key.

You can also use the addition (+) operator, and anything you can think of, to compute the key.

index.js
const obj = { country: 'Chile', name: 'Tom', }; // โœ… Get object value by variable key const myVar = 'c'; console.log(obj[myVar + 'ountry']); // ๐Ÿ‘‰๏ธ "Chile"

Here's an example of using a ternary operator, which is very similar to an if/else statement.

index.js
const obj = { country: 'Chile', name: 'Tom', }; // โœ… Get object value by variable key const myVar1 = 'country'; const myVar2 = 'name'; console.log(obj[5 > 0 ? myVar1 : myVar2]); // ๐Ÿ‘‰๏ธ "Chile"

After the expression gets evaluated, it returns the value of the myVar1 variable and the object is accessed at the key country.

You can also use the computed property names approach when setting keys on an object.

index.js
const obj = { country: 'Chile', name: 'Tom', }; const myVar = 'age'; obj[myVar] = 30; console.log(obj[myVar]); // ๐Ÿ‘‰๏ธ 30

In this example, we used a variable to set the age key on the object and then we used bracket notation to evaluate the variable and access the key.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee