Get an Object's Value by Variable Key in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 27, 2022

banner

Photo from Unsplash

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"
You have to use the bracket [] notation syntax when a variable has to be evaluated to a specific key.

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

index.js
const obj = { country: 'Chile', name: 'Tom', }; // ✅ Get object value by variable key const myVar = 'country'; console.log(obj[myVar]); // 👉️ "Chile"

The variable between the brackets gets evaluated before accessing the object at the specific key.

You can also use the addition (+) operator, or any other expression 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 the 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"
If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.

After the expression gets evaluated, it returns the value of the myVar1 variable.

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

We used a variable to set the age key on the object and then used bracket notation to evaluate the variable to access the key.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.