When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation:
object.property
object['property']
Let's explore a scenario using the latter method:
const user = {
firstName: 'John',
lastName: 'Doe'
}
const prop = 'firstName';
console.log(user[prop]); //"John"
Now, my question is about utilizing bracket notation for array properties where the value inside the brackets represents a path to an array. Consider the following example:
const user = {
firstName: 'John',
lastName: 'Doe',
nicknames: [
{ id: 1, value: 'Johnny'},
{ id: 2, value: 'JD'},
{ id: 3, value: 'Dude'}
]
}
const prop = 'nicknames[2].value';
console.log(user[prop]);
With the console.log()
, I intend to output JD
. However, this approach fails as there is no property named nicknames[2].value
within user
;
So the question remains: How can bracket notation be effectively used in such scenarios involving array properties?