0

I am using react and working with a basic export file containing contracts, here's how it looks like:

export const contract1 = ....
export const contract2 = ....
export const contract3 = ....
export const contract4 = ....

Then in another file, I import them with:

import * as P from "../filepath"

const function = (contractVariable)=>{
     let contract =  P.contractVariable;
...
}

I want to select the contract being exported according to the variable in my function. Is that possible?

Ivan Bila
  • 747
  • 7
  • 9
Yan Digilov
  • 166
  • 7

2 Answers2

2

This is how you can dynamically access object properties.

let contract =  P[contractVariable];
Ivan Bila
  • 747
  • 7
  • 9
Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Nice! see also [this](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable#4244912) and [this](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Ivan Bila May 25 '21 at 05:32
0

Answer above is very helpful. I found another issue which was my variable was actually only the id (1, 2, 3, or 4). With that help I got it by using:

let contract = P.[`contract`+`${contractId}`]
Yan Digilov
  • 166
  • 7