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
Use recursion
const pr = (data) => {
console.log(data.name);
data.forms.forEach((f) => pr(f));
};
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;
}
// 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)