To get started with the dynamic access to object properties in JS, let’s first take a look at how you could get access to a static object property.
const user = {
age: 25,
name: 'Jack'
}
console.log(user.name);
console.log(user.age);
It’s easy to get access to a static object property in JS using the dot notation. The problem is that you can’t use this approach when you don’t know in advance which properly you’re going to need.
To access the object property dynamically in JS, you need to pass the property name as a string in square brackets.
const user = {
age: 25,
name: 'Jack'
}
let key = 'age';
console.log(user[key]); // 25
key = 'name';
console.log(user[key]); // Jack
As the value of the variable key
changed, we got access to the
different properties of the user
object.
The most common way to access the object properties in JavaScript is the dot.
You write something like user.age
or user.name
to get access to the
properties age
and name
of the object user.
It works perfectly until you need to design an algorithm that doesn’t know in advance which property it needs to access.
Here’s a simplified example of what it might look like.
const printObjectProperty = (obj, key) => {
console.log(obj[key]);
}