I'm currently working on a project where I need to dynamically derive a table column structure from any type of generic object. This object may contain properties of various types, and each property that is not an object itself should be considered a separate column in the table. If a property happens to be another object, then its properties should also translate into columns (and so forth).
For example, let's take a look at the following object.
export interface Event {
name: string;
meta: {
created: Date,
updated: Date,
},
some_data: {
nested_data: {
some_nested_data: string;
}
}
}
The goal is to display a list of these objects in a structured table format as shown below.
name | created | updated | some_nested_data |
---|---|---|---|
Bob | 1/1/2020 | 2/1/2020 | some value |
Anna | 1/2/2020 | 2/2/2020 | some value |
Note: The objective is to make this work seamlessly for any type of generic object.
Approach Attempted
To tackle this challenge, I have introduced a Column class.
export class Column extends LinkedList<ObjectProperty>
This class is complemented by the following code snippet.
export type ObjectProperty = { name: string, type: string }
export interface ILinkedList<T> {
insertInBegin(data: T): Node<T>;
insertAtEnd(data: T): Node<T>;
deleteNode(node: Node<T>): void;
traverse(): T[];
size(): number;
search(comparator: (data: T) => boolean): Node<T> | null;
}
export class Node<T> {
public next: Node<T> | null = null;
public prev: Node<T> | null = null;
constructor(public data: T) {}
}
By utilizing LinkedList<ObjectProperty>
, I can access any object property value within a column by providing an array of property names (using the traverse()
function to retrieve the array) and navigating through the object until reaching the desired value.
With this setup, I believe it is possible to display the data in the desired tabular form using the following methodology.
<thead>
<tr>
<ng-container *ngFor="let column of columns">
<th *ngFor="let property of column.traverse(); let i = index">
{{ column.getLast().data.name }}
</th>
</ng-container>
</tr>
</thead>
<tbody>
<tr *ngFor="let object of dataSorted; let i = index">
<td *ngFor="let column of columns">
{{ getColumnValue(column, object) }}
</td>
</tr>
</tbody>
Challenge Faced
I find myself struggling when it comes to mapping an object's keys to an array of Columns containing a linked list populated with object properties.
I have experimented with different functions involving Object.keys(object).map()
and multiple recursive approaches, but I am unable to arrive at a concrete solution, especially considering the support needed for nested objects.
In essence: My aim is to correlate a generic object's properties to an array of Column objects (refer to Column class).
Any guidance or assistance in solving this matter would be greatly appreciated!
Please feel free to request additional information or resources if necessary.