在angular 5中迭代一个复杂的JSON结构 [英] iterate a complex JSON structure in angular 5
本文介绍了在angular 5中迭代一个复杂的JSON结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在angular 5中迭代JSON?一直在寻找很多管道概念,但是它不适用于复杂的json,如下所示.我需要使用以下类型的数据创建可扩展表,我被困在读取此json的过程中.
how to iterate a JSON in angular 5? Have been searching a lot a got a pipe concept but it does not work with complex json something like below . I need to create expandable table using below type of data, I am stuck in reading this 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
获取对象的所有属性.如果要在有角度的模板中使用它,则必须在组件中创建一个包装它的方法.
You can use Object.keys
to get all properties of an object. If you want to use it in an angular template, you have to create a method in your component that wraps it.
此处我整理了一个简单的示例,使用模板创建了嵌套表.
Here I hacked together a simple example, using a template to created nested tables.
您会明白的:
//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 {}
这篇关于在angular 5中迭代一个复杂的JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文