'Access property to the infinity

I have the following form object:

{
    "name":"form name",
    "forms":[
        {
            "name":"form 1",
            "forms":[
                ...
            ]
        }
    ]
}

Forms can contain forms inside them.

The idea was to print all the form names.

I did the following:

forms.forEach(form -> {
  console.log(form.name);
  
  form.forms.forEach(f -> {
     console.log(f.name);

     f.forms.forEach(...);
  })
});

I have no idea how many forms can be inside so how can I do this to infinity.

Thanks



Solution 1:[1]

You should use recursion. Could be something like this:

function logFormName(data) {
  if (data.name) {
    console.log(data.name)
  }
  if (data.forms) {
    return data.forms.forEach((form) => logFormName(form))
  }
  return;
}

Solution 2:[2]

Use recursion

const pr = (data) => {
  console.log(data.name);
  data.forms.forEach((f) => pr(f));
};

Solution 3:[3]

// forms data
let forms = {
  "name":"form name",
  "forms":[
      {
          "name":"form 1",
          "forms":[
              
          ]
      }
  ]
}


// recursive function to iterate through each form
// and print name of the form
function printForms(forms) {

if(forms.hasOwnProperty("forms")){
  console.log(forms.name);
  
  // iterate over each form        
  forms.forms.forEach(form => {
  
    // recursive call           
    printForms(form);
  })
}
}

// call function to print name of each form
printForms(forms)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Konstantin Samarin
Solution 2 Minh Nguyên
Solution 3 Farhan Ali