Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
¿Cómo obtener el número de todas las rutas de encuesta posibles?

Hay un cuestionario que muestra una pregunta dependiendo de la respuesta. El archivo JSON contiene la identificación de las preguntas que se muestran cuando selecciona. El objeto de la pregunta se ve así:

 const quiz = [ { id: "1", question: "question1", answer1: { text: "answ1", nextQuestion: "2", }, answer2: { text: "answ2", nextQuestion: "3", }, }, { id: "2", question: "question2", answer1: { text: "answ1", nextQuestion: "", }, answer2: { text: "answ2", nextQuestion: "", }, }, { id: "3", question: "question3", answer1: { text: "answ1", nextQuestion: "", }, answer2: { text: "answ2", nextQuestion: "", }, }, ];

¿Cómo puede pasar por todas las ramas posibles del cuestionario y formar tal objeto con datos?

 { branches: { questionsList: [ [ { "question1": "answ1" }, { "question2": "answ1" }, ], [ { "question1": "answ1" }, { "question2": "answ2" }, ], [ { "question1": "answ2" }, { "question3": "answ1" }, ], [ { "question1": "answ2" }, { "question3": "answ2" }, ], ], }, },

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Esta puede ser una implementación para lograr el objetivo deseado.

Fragmento de código

 const getAllBranches = arr => { // first create a map/object to quickly access each question by id const qMap = arr.reduce((f, i) => ({ ...f, [i.id]: {...i, ch: [ // keep track of 'children' using this 'ch' array ...Object.keys(i) .filter(k => k.includes('answer')) // any key with 'answer' is included .map(k => ({...i[k]})) ]} }), {}); // recursive function to get the desired objective const recurGet = ({id, question, ch}) => ( ch.map(({text, nextQuestion}) => ( nextQuestion.length === 0 // if no 'nextQuestion', simply return an object ? { [question] : text } : recurGet(qMap[nextQuestion]).map(ob => ({ [question]: text, ...ob // if else, recursive-call and append question-answer to each result })) )) ); return recurGet(qMap[arr[0].id]); }; const quiz = [{ id: "1", question: "question1", answer1: { text: "answ1", nextQuestion: "2", }, answer2: { text: "answ2", nextQuestion: "3", }, }, { id: "2", question: "question2", answer1: { text: "answ1", nextQuestion: "", }, answer2: { text: "answ2", nextQuestion: "", }, }, { id: "3", question: "question3", answer1: { text: "answ1", nextQuestion: "", }, answer2: { text: "answ2", nextQuestion: "", }, }, ]; // add the branches into a new object to meet // the desired objective's structure const resObj = { branches: { questionsList: getAllBranches(quiz) } }; console.log(resObj);

Explicación

Se han incluido comentarios relevantes en el código anterior.

Publique cualquier pregunta en los comentarios para obtener una explicación más detallada, si es necesario.

NOTA : Proporcione más casos de prueba (como con más de 2 respuestas, etc.) para probar la solución de manera efectiva.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda