Untitled
unknown
plain_text
a year ago
1.7 kB
5
Indexable
interface Node { value: string; label: string; children?: Node[]; } const data = [ "users.customers.create", "users.customers.delete", "users.internal_users.list" ]; const createNodes = (data: string[]): Node[] => { const nodesMap: { [key: string]: Node } = {}; data.forEach(item => { const parts = item.split('.'); let currentLevel = nodesMap; parts.forEach((part, index) => { if (!currentLevel[part]) { currentLevel[part] = { value: part, label: part.charAt(0).toUpperCase() + part.slice(1), children: [] }; } if (index === parts.length - 1) { // Remove the empty children array for the last item delete currentLevel[part].children; } else { currentLevel = currentLevel[part].children!.reduce((map, node) => { map[node.value] = node; return map; }, {} as { [key: string]: Node }); } }); }); const convertToArray = (nodesMap: { [key: string]: Node }): Node[] => { return Object.values(nodesMap).map(node => ({ ...node, children: node.children && node.children.length ? convertToArray(node.children.reduce((map, child) => { map[child.value] = child; return map; }, {} as { [key: string]: Node })) : undefined })); }; return convertToArray(nodesMap); }; const nodes = createNodes(data); console.log(JSON.stringify(nodes, null, 2));
Editor is loading...
Leave a Comment