json - angular - 从 JSON 中读取属性名称作为列名,并在列中显示另一个属性值
问题描述
我在结构中有 json 文件(显示其对象之一)为
[
...
{
"Tag": "YearOfOperation",
"Type": 9,
"Value": "2018"
}
...
]
在 html 模板上,我有一张桌子。在表格的“运营年份”行上,我想显示“2018”。我正在尝试遍历 json(即按行/标签名称查找)并显示 json 的显示“值”。在 html 模板中,我想要类似的东西:
<table>
<tr>
<td> Year Of Operation </td> // row name is hard coded. it doesn't depend on json
<td> display json "Value" where "Tag"=="YearOfOperation" </td>
</tr>
</table>
app.component.ts
public productData: any;
ngOnInit() {
this.getJSON().subscribe(res => {
this.productData = JSON.parse(res);
})
}
public getJSON(): Observable<any> {
return this.http.get('./images/output_test.json')
.pipe(
map(res => res)
)
// .catch((error:any) => console.log(error));
}
先感谢您。
解决方案
如果您的 JSON 如下所示,并且我正确理解了您的问题,那么这应该适合您:
应用程序.json
[
{ "Tag":"Location", "type": 9, "Value":"Europe" },
{ "Tag":"Location", "type": 10, "Value":"US" },
{ "Tag":"YearOfOperation", "type": 9, "Value":"2016" },
{ "Tag":"YearOfOperation", "type": 10, "Value":"2018" },
{ "Tag":"TaxId", "type": 9, "Value":"txn123" },
{ "Tag":"TaxId", "type": 10, "Value":"txn124" }
]
app.component.html
<table>
<thead><tr><th>Location</th><th>Year Of Operation</th><th>Tax ID</th></tr></thead>
<tbody>
<tr *ngFor="let product of products">
<td *ngIf="product?.Tag === 'Location'; else blankValue">{{product?.Value}}</td>
<td *ngIf="product?.Tag === 'YearOfOperation'; else blankValue">{{product?.Value}}</td>
<td *ngIf="product?.Tag === 'TaxId'; else blankValue">{{product?.Value}}</td>
</tr>
</tbody>
</table>
<ng-template #blankValue><td></td></ng-template>
app.component.ts
public products: any;
ngOnInit() {
this.getJSON().subscribe(res => {
this.products = <Array<{}>>res;
})
}
public getJSON(): Observable<any> {
return this.http.get('./images/output_test.json')
.pipe(
map(res => res),
catchError((error) => { console.error(error); return error;})
);
}
app.component.css
th {
padding:10px;
border:1px solid black;
}
td {
padding:10px;
border:1px solid black;
}
推荐阅读
- javascript - 当鼠标在img上移动时,如何在其他元素的顶部制作一个按钮?
- python - django rest 框架序列化器 - 不返回空列表字段
- hugo - 如何在 Hugo 中检查当前范围内的变量?
- css - 是否可以根据被定位元素的右下角绝对定位元素?
- sql - 带有批次的 BigQuery ARRAY_AGG
- node.js - Mongoose:查询数组的长度是否> 0
- oracle-apex - APEX Interactive Grip 更新 PL/SQL 代码太长
- vba - VBA 将 Word Doc 打印为 PDF,并使用 Mailmerge 字段中的密码
- sql-server - 将数据从一个位置传输到另一个具有相同数据库和表架构的位置
- reactjs - 如何在渲染之前将发送数据发送到组件?