Use property using the value of multiple variables

I know there’s a possibility like this:

let eventSelected = "333";

let bestResult = result.personal_records[eventSelected]?.single?.best 
                 //search like this: result.personal_records.333?.single?.best

but when I have more variables, I cannot to like this:

let eventSelected = "333";
let type = "average"

let bestResult = result.personal_records[eventSelected]?[type]?.best //error syntax

Is there some solution

>Solution :

For optional chaining with dynamic properties, use ?.[prop]. In this case, it would be ?.[type]?.best.

Leave a Reply