JSFiddle - React, Tailwind, and code Playground

by artgas_pro

JavaScript

function mapPaths(data) {
  const paths = {
    number: 0,
    list: [],
  };

  function traverse(currentPath, currentQuestionId) {
    const currentQuestion = data[currentQuestionId];

    // If current question does not exist or has no answers, add current path to the list of paths
    if (!currentQuestion || !currentQuestion.answers) {
      paths.list.push(currentPath);
      paths.number++;
      return;
    }

    // Iterate over each answer for the current question
    for (const answer of currentQuestion.answers) {
      const newPath = [...currentPath, { [currentQuestion.question]: answer.text }];
      traverse(newPath, answer.id);
    }
  }

  traverse([], "0");

  return { paths };
}

// Usage example:
const data = {
  "0": {
    question: "What is your marital status?",
    answers: [
      {
        text: "Single",
        id: "1",
      },
      {
        text: "Married",
        id: "2",
      },
    ],
  },
  "1": {
    question: "Are you planning on getting married next year?",
    answers: [
      {
        text: "Yes",
        id: false,
      },
      {
        text: "No",
        id: false,
      },
    ],
  },
  "2": {
    question: "How long have you been married?",
    answers: [
      {
        text: "Less than a year",
        id: false,
      },
      {
        text: "More than a year",
        id: "3",
      },
    ],
  },
  "3": {
    question: "Have you celebrated your one year anniversary?",
    answers: [
      {
        text: "Yes",
        id: false,
      },
      {
        text: "No",
        id: false,
      },
    ],
  },
};

const result = mapPaths(data);
console.log(result);