1

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

 1 year ago
source link: https://typeofnan.dev/access-dynamic-property-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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!


Subscribe to my newsletter

Join 2,543+ other developers and get free, weekly updates and code insights directly to your inbox.

  • No spam
  • Unsubscribe whenever
Email Address

Powered by Buttondown

© 2023 Nick Scialli


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK