0

I have 2 arrays. The one contains the name of all the keys of the 2nd array like the following.

    const additionalFields = ['phoneNumbers', 'ageOrDobs', 'genders', 'usernames', 'employments', 'educations', 'websites', 'affiliatedOrganizations'];

const fields= [{
    affiliatedOrganizations: []
    ageOrDobs: []
    educations: []
    emails: [{…}]
    employments: []
    genders: []
    locations: [{…}]
    names: [{…}]
    phoneNumbers: []
    usernames: []
    websites: []
}]

Now, I want to loop through the additionalFields based on the value I receive I want to check if the key of fields have length greater than 0. For example.. fields.phonenNumbers.length > 0 but the key phoneNumbers will be coming from loop

additionalFields.map((opts) => {
     if(fields.opts.length > 0){ //this one doesn't work...
        //do something
     }
}

I am using typescript and fields have a interface related to the values in it as shown above. Please help me with this... thank you!!

Nagesh Katna
  • 679
  • 2
  • 7
  • 27

1 Answers1

1

Just use the Bracket notation:

additionalFields.map((opts) => {
  if(fields[opts].length > 0){ //this one doesn't work...
    //do something
  }
}

Example:

const person = {
  firstname: 'John',
  lastname: 'Doe'
}

const key = "firstname"
console.log(person[key]) // John
Lars Flieger
  • 2,421
  • 1
  • 12
  • 34