0

Considering i got a such code:

type RouteConfig = {
  path: string;
  text: string;
  routes?: RouteConfig[];
};

const routes: RouteConfig[] = [
  {
    path: "/",
    text: "home"
  },
  {
    path: "/user",
    text: "user",
    routes: [
      {
        path: "/user/info",
        text: "user info"
      },
      {
        path: "/user/books",
        text: "user books"
      }
    ]
  }
];

const routeEntries = ["/", "/user", "/user/info", "/user/books"]; // ?? how to get it Programmatically instead of hard coding.

The routes is a tree-like nested object array, each node might contains sub routes node.

The question is simple, how do i get routeEntries based on existed routes defined above?

1 Answer 1

1

You can create a recursive function that will gather every path value, like :


Playground

type RouteConfig = {
  path: string;
  text: string;
  routes?: RouteConfig[];
};

const routes: RouteConfig[] = [
  {
    path: '/',
    text: 'home',
  },
  {
    path: '/user',
    text: 'user',
    routes: [
      {
        path: '/user/info',
        text: 'user info',
      },
      {
        path: '/user/books',
        text: 'user books',
      },
    ],
  },
];

function extractPath(data: RouteConfig[]) {
  return data.reduce((tmp: string[], x) => {
    if (typeof x.routes !== 'undefined') {
      tmp = [
        ...tmp,
        ...extractPath(x.routes),
      ];
    }

    tmp.push(x.path);

    return tmp;
  }, []);
}

const routeEntries = extractPath(routes);

console.log(routeEntries);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.