如何在 angular 5 中迭代 JSON?一直在搜索一个管道概念,但它不适用于复杂的 json,如下所示。我需要使用以下类型的数据创建可扩展表,我被困在读取这个 json 中。
data = [{
"Items" : [ {
"Key" : "9009",
"type" : "fsdf",
"name" : "sdfsdfn",
"spec" : "dsfsdfdsf",
"Attributes" : {
"category" : "Mobile",
"orderDate" : "2019-03-07 14:40:49.2",
"startDate" : "2019-03-07 14:40:49.2",
"status" : "CREATED"
},
"characteristics" : [ ],
"relatedItems" : {
"contains" : [ "1", "2", "3"]
},
"sellable" : false
}, .... {} ]
可以使用Object.keys
获取对象的所有属性。如果要在角度模板中使用它,则必须在组件中创建一个包装它的方法。
在这里,我拼凑了一个简单的示例,使用模板创建嵌套表。
你会得到这个想法:
//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<ng-template #table let-obj="obj">
<table style="border: 1px solid black">
<thead>
<tr>
<td *ngFor="let key of getKeys(obj)">
{{key}}
</td>
</tr>
</thead>
<tbody>
<tr>
<td *ngFor="let value of getValues(obj)">
<div *ngIf="isValue(value)">
{{value}}
</div>
<div *ngIf="!isValue(value)">
<ng-container *ngTemplateOutlet="table;context:ctx(value)"></ng-container>
</div>
</td>
</tr>
</tbody>
</table>
</ng-template>
<div *ngFor="let d of data">
<ng-container *ngTemplateOutlet="table;context:ctx(d)"></ng-container>
</div>
`,
})
export class App {
data:any[];
constructor() {
this.data = [ {
"Key" : "9009",
"type" : "fsdf",
"name" : "sdfsdfn",
"spec" : "dsfsdfdsf",
"Attributes" : {
"category" : "Mobile",
"orderDate" : "2019-03-07 14:40:49.2",
"startDate" : "2019-03-07 14:40:49.2",
"status" : "CREATED"
},
"characteristics" : [ ],
"relatedItems" : {
"contains" : [ "1", "2", "3"]
},
"sellable" : false
}];
}
ctx(obj) {
return { obj };
}
getKeys(obj) {
return Object.keys(obj);
}
getValues(obj) {
return Object.values(obj);
}
isValue(obj) {
return (obj !== Object(obj));
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}