I have a nested tree of table columns. Here are the typescript types.
export interface TableLeafColumn {
label: string;
key?: string;
}
export interface TableContainerColumn {
label: string;
columns: TableColumn[];
}
// Union type to represent either a leaf or container column
export type TableColumn = TableLeafColumn<T> | TableContainerColumn;
Here’s an example of such a type:
const columns: TableColumn[] = [
{
label: "Name",
key: "name",
},
{
label: "Details",
columns: [
{
label: "Age",
key: "age",
},
{
label: "Address",
columns: [
{ label: "City", key: "city" },
{ label: "Country", key: "country" },
],
},
],
},
];
I would like a function called flattenColumns
that will return TableColumn[][]
. For example, the input above would return:
const result = [
[
{ label: "" }, // placeholder for Name
{ label: "Details", colSpan: 3 }
],
[
{ label: "" }, // placeholder for Name
{ label: "" }, // placeholder for Age
{ label: "Address", colSpan: 2 }
],
[
{ label: "Name", key: "name" },
{ label: "Age", key: "age" },
{ label: "City", key: "city" },
{ label: "Country", key: "country" },
]
]
I have tried to write the function, but nothing worked. The tricky party is adding the placeholders, so that every leaf column appears at the bottom.
Not sure if the result I gave above is the best representation for this, but I want to render such table headers inside an HTML table, and I figured that format would be the easiest to utilise.