TypeOfNaN

How to access an object property with a dynamically-computed name in JavaScript

Nick Scialli
March 18, 2023

Using a dynamic object key name is critical for creating dynamic JavaScript applications. Let’s consider the following object that represents a person:

const person = {
  name: 'Wilma',
  age: 27,
};

Dot notation doesn’t work

If we know what key we need to access, we can simply use dot notation to get it. For example, we can console.log ther person’s name:

console.log(person.name);
// Wilma

But what if we have a variable that represents the key we want? In our example, that variable can be either "name" or age:

const person = {
  name: 'Wilma',
  age: 27,
};

const key = 'age';

We can’t use dot notation in this instance. Trying to get person.key will fail because JavaScript will look for a key property on person, which doesn’t exist.

Bracket notation works!

Fortunately, we can use bracket notation in this case: person[key]

const person = {
  name: 'Wilma',
  age: 27,
};

const key = 'age';

console.log(person[key]);
// 27

And there you have it! You can now use a dynamic key to access a property on a JavaScript object.

If you'd like to support this blog by buying me a coffee I'd really appreciate it!

Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli