I have a nested JSON structure which needs to be represented in a table. The structure is:
students = [
{
"id": "1",
"name": "Ram",
"subjects": [
{
"id": "101",
"name": "Maths",
"exams": [
{
"id": "1",
"name": "exam1",
"score": "90"
},
{
"id": "2",
"name": "exam2",
"score": "80"
}
]
},
{
"id": "102",
"name": "English",
"exams": [
{
"id": "1",
"name": "exam1",
"score": "95"
},
{
"id": "2",
"name": "exam2",
"score": "85"
}
]
}
]
},
{
"id": "2",
"name": "Ajay",
"subjects": [
{
"id": "101",
"name": "Maths",
"exams": [
{
"id": "1",
"name": "exam1",
"score": "80"
},
{
"id": "2",
"name": "exam2",
"score": "90"
}
]
},
{
"id": "102",
"name": "English",
"exams": [
{
"id": "1",
"name": "exam1",
"score": "85"
},
{
"id": "2",
"name": "exam2",
"score": "95"
}
]
}
]
}
];
I am using p-table from pringng. I need to have a outlook of table as follows:
Could anyone please share their experiences in rendering nested json.
I have already tried nested tables and nested loops in div but the layout messed up big time.
Sample code with p-table(primeng):
<p-table #dt [value]="students" [responsive]="true" [paginator]="true" [rows]="5"
[rowsPerPageOptions]="[5,10,25,50]" [autoLayout]="true" [globalFilterFields]="['name']" [scrollable]="true" scrollHeight="400px" frozenWidth="300px" >
<ng-template pTemplate="header">
<tr class="table-header">
<th style="width:18%" class="table-header-column" >
<span>Student Name</span>
</th>
<th style="width:8%" class="table-header-column" rowspan="2">
Subject
</th>
<th style="width:6%" class="table-header-column" rowspan="2">
Marks
</th>
</tr>
<tr class="table-header">
<th>
<input placeholder="Search Student" pInputText size="25" type="text"
(input)="dt.filterGlobal($event.target.value, 'contains')">
</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-student>
<div *ngFor="let subject of student.subjects; index as i" class="table-cell-color">
<tr *ngFor="let exam of subject.exams; index as j" class="table-cell-color">
<td>{{student.name}}</td>
<td>{{subject.name}}</td>
<td>{{exam.score}}</td>
</tr>
</div>
</ng-template>
</p-table>
Output:
Sample of mdbTable with mdbBootstrap:
<table class="table table-bordered" mdbTable mdbTableScroll scrollY="true" scrollX="true" >
<thead>
<tr class="table-header">
<th >Student Name</th>
<th >Subject</th>
<th >Marks</th>
</tr>
</thead>
<tbody>
<tr mdbTableCol *ngFor="let student of students" >
<div *ngFor="let subject of student.subjects;">
<div *ngFor="let exam of subject.exams; index as i">
<td >{{student.name}}</td>
<td >{{subject.name}}</td>
<td >{{exam.name}}</td>
</div>
</div>
</tr>
</tbody>
</table>
Output:
Would be great if someone can share their thoughts. I am open to switch to any other library if needed.