-1

So below I have a variable newVal. Inside that variable are objects such as profileNum1 and inside that userEmail which I can access via

let profile = newVal.profileNum1.userEmail;

which would return a string such as 'users@email.com'


    let newVal = JSON.parse(value);

                  for (let z = 0; z < 100; z++) {
                    console.log('LOOP HAS BEGAN RUNNING' + z);
                    let profile = newVal.profileNum1.userEmail;
                    console.log('LOOK FOR MEEEEEEEEEEEEEE' + profile);

Now I need to basically add the variable z into profileNum in replacement of 1.

I tried achieving this via let profile = newVal.profileNum + z.userEmail;

Which does not work it just returns NaN so I am assuming I am unable to do it that way since with z = 1 during the loop it should return a result when it hits z = 1 in the loop but it still returns NaN. I am pretty stumped on how I can add the variable Z into that and it still use it to select the object profileNum1, profileNum2, etc. Any help would be appreciated =]

CodingIsFun33
  • 433
  • 3
  • 14

1 Answers1

0

Use bracket notation:

let profile = newVal["profileNum" + z].userEmail;

This will parse profileNum0, profileNum1, profileNum2 etc. and access it - basically doing this:

let profile = newVal.profileNum0.userEmail; // When z is 0
let profile = newVal.profileNum1.userEmail; // When z is 1
let profile = newVal.profileNum2.userEmail; // When z is 2
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79