[SOLVED] loop through a dynamic key of an object in a array


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!!


Just use the Bracket notation:

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


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

const key = "firstname"
console.log(person[key]) // John

Answered By – Lars Flieger

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *