Limboer
Limboer

Reputation: 414

Flat nested object array with one property extracted in TypeScript

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?

Upvotes: 0

Views: 33

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23515

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);

Upvotes: 1

Related Questions