Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

27
Vistas
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

7 months ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Use recursion

const pr = (data) => {
  console.log(data.name);
  data.forms.forEach((f) => pr(f));
};
7 months ago · Juan Pablo Isaza Denunciar

0

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;
}
7 months ago · Juan Pablo Isaza Denunciar

0

// 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)
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos