Assume I have this object routes which represent my website routes tree:
const r = {
HOME: "start",
ACCOUNT: {
HOME: "account",
PROFILE: "profile",
ADDRESSES: {
HOME: "addresses",
DETAIL: ":addressId",
},
},
ESHOP: {
HOME: "eshop",
INVOICES: "invoices",
ORDERS: {
HOME: "orders",
DETAIL: ":orderId",
},
},
INVENTORY: {
HOME: "warehouse",
CATEGORIES: {
HOME: "categories",
CATEGORY: {
HOME: ":categoryId",
PRODUCTS: {
HOME: "products",
PRODUCT: ":productId",
},
},
},
},
};
I’m trying to build a compact and elegant function to return the full path from a known object keys path, like this:
buildRoute(r, "r.ACCOUNT.ADDRESSES.DETAIL")
// should return this string: "start/account/addresses/:addressId"
or
buildRoute(r, "r.INVENTORY.CATEGORIES")
// should return this string: "start/warehouse/categories"
or
buildRoute(r, "r.INVENTORY.CATEGORIES.CATEGORY.PRODUCTS.PRODUCT")
// should return this string: "start/warehouse/categories/:categoryId/products/:productId"
Where "r" is my object routes, "HOME" is the fixed key of any path/subpath and the "slash" must be inserted in all subroutes except the last one.
Of course I’ll pass the data as a string, not a value.
How can i achieve this with clean and not too long code? Typescript solution including types would be better and appreciated.
2
Answers
You could split the given string into its parts and then walk down the hierarchy accordingly, building the result string as you go:
If you want it compact, elegant, and to have autocompletions, use Proxy style, the same one libs like tRPC use