我正在接收已旋转的结果的数据对象,而且我无法更改返回给我的结构。我现在唯一的选择就是操纵数据来解析我需要的方式。JavaScript透视数据并从对象生成动态表格
这里是我的结果如下:
// Object from service
let dataObj = [{
CostCenter: '12345',
HasLevel1Access: 'No',
HasLevel2Access: 'No',
HasLevel3Access: 'Yes',
FirstName: 'Bob',
LastName: 'Jones',
UID: '12345'
},
{
CostCenter: '555',
HasLevel1Access: 'Yes',
HasLevel2Access: 'No',
HasLevel3Access: 'Yes',
FirstName: 'Tommy',
LastName: 'C',
UID: '6789'
},
{
CostCenter: '51112',
HasLevel1Access: 'Yes',
HasLevel2Access: 'No',
HasLevel3Access: 'Yes',
FirstName: 'Smithson',
LastName: 'J',
UID: '8888'
}];
从这个数据,我需要一张桌子。这里的诀窍是我需要使用一些属性名称作为列标题,但排除其他属性。
我的表是非常基本的,它包含了人的名称,然后所有的动态列名:
<table class="table table-condensed" border="1">
<thead>
<tr>
<th>Employee Name</th>
<th *ngFor="let m of columnNames">{{ m }}</th>
</tr>
</thead>
<tbody>
<!-- Example Record 0 -->
<tr>
<td>Bob Jones</td>
<td>No</td>
<td>No</td>
<td>Yes</td>
</tr>
<!-- Example Record 0 -->
</tbody>
</table>
我为了获得列名做的第一件事是创建IgnoreColumns
数组这是我不想排除在表中自己专栏的属性名称。
// Hold all of the column names
private columnNames = [];
// Ignore these columns, they dont get printed as headers
private ignoreColumns = ['CostCenter', 'FirstName', 'LastName', 'UID'];
然后我挂绕在结果集中的第一条记录,并推动所有的属性名称的数组不在我们ignoreColumns
阵列。这给我留下了一个独特的动态列阵列。
// Find all the keys in our first result
for (var p in dataObj[0]) {
// Get the key names
if (dataObj[0].hasOwnProperty(p)) {
// If this key name doesnt already exist in the array AND its not in our ignored list push them to our array
if (!_.includes(this.columnNames, p) && !_.includes(this.ignoreColumns, p)) {
this.columnNames.push(p);
}
}
}
我被困在这一点。我能够创建具有标题的表结构,但我不知道应该如何让数据在表格中正确的列下对齐。
这就是我要在我的最终输出:
<table class="table table-condensed" border="1">
<thead>
<tr>
<th>Individual</th>
<th>HasLevel1Access</th>
<th>HasLevel2Access</th>
<th>HasLevel3Access</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bob Jones</td>
<td>No</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Tommy C</td>
<td>Yes</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Smithson J</td>
<td>Yes</td>
<td>No</td>
<td>Yes</td>
</tr>
</tbody>
</table>
这里是我所在的地方在plunkr:http://plnkr.co/edit/9WygBXsQaDaxTMudb7ZB?p=preview
对如何处理这有什么建议?
以及该死的,这似乎工作 - 我花了更长的时间来写的比你指出了一个简单的答案:)问题。谢谢! – SBB
哈哈..很高兴它帮助兄弟 – jitender