In Typescript (and Javascript for that matter), you can access an object's properties using the dot notation or the bracket notation:
object.property
object['property']
Using a concrete example for the latter:
const user = {
firstName: 'John',
lastName: 'Doe'
}
const prop = 'firstName';
console.log(user[prop]); //"John"
My question is if/how bracket notation can be used for array properties where the value in the bracket is a path to an array. Here is an 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]);
My goal with the console.log()
would be to print JD
, but this example would fail because there is, of course, no property of user
called nicknames[2].value
;
How can I use bracket notation in this manner with array properties?