如何在 Angular 中循环遍历未知属性的数组对象

所以我发现很难表达我的问题的标题,我想做的是循环遍历对象数组,但我不知道对象的属性,因为它是动态的并且来自数据库。


下面是一个数组对象的例子:


[{

    "id": 9,

    "event_id": 13,

    "details": {

        "firstname": "Ralph",

        "lastname": "Marvin",

        "email_address": "ralphmarvin@email.com",

        "phone_number": "0987654321"

    }

}, {

    "id": 10,

    "event_id": 13,

    "details": {

        "firstname": "John",

        "lastname": "X Doe",

        "email_address": "john_x_doe120@xmail.com",

        "phone_number": "0009876543"

    }

}, {

    "id": 11,

    "event_id": 13,

    "details": {

        "firstname": "Wari",

        "lastname": "Gumah",

        "email_address": "gumahwarihanna@eeee.com",

        "phone_number": "120029182765"

    }

}]

我想在如下所示的表格中显示对象的详细信息部分:


firstname     lastname      email_address       phone_number

以及每个值下的适当值。使用 Angular 8。


我只是不知道如何使用 *ngFor 来访问我什至不知道的属性。我正在尝试做的甚至是可能的,如果是,请告诉我如何做。


谢谢!。


慕的地6264312
浏览 233回答 2
2回答

慕姐4208626

您可以通过keyvalue pipe访问详细信息对象来迭代对象键/值作为内部 for 循环 。网址:&nbsp; <table>&nbsp; &nbsp; &nbsp;<tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;<th>Firstname</th>&nbsp; &nbsp; &nbsp; &nbsp;<th>lastname</th>&nbsp; &nbsp; &nbsp; &nbsp;<th>email_address</th>&nbsp; &nbsp; &nbsp; &nbsp;<th>phone_number</th>&nbsp; &nbsp; &nbsp;</tr>&nbsp; &nbsp; &nbsp;<tr *ngFor="let listItem of yourList" >&nbsp; &nbsp; &nbsp; &nbsp;<td *ngFor="let innerItem of listItem.details | keyvalue">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{{innerItem.value}&nbsp; &nbsp; &nbsp; &nbsp;</td>&nbsp; &nbsp; &nbsp;</tr>&nbsp; &nbsp;</table>填充列表&nbsp; &nbsp;yourList = [{&nbsp; &nbsp; "id": 9,&nbsp; &nbsp; "event_id": 13,&nbsp; &nbsp; "details": {&nbsp; &nbsp; &nbsp; "firstname": "Ralph",&nbsp; &nbsp; &nbsp; "lastname": "Marvin",&nbsp; &nbsp; &nbsp; "email_address": "ralphmarvin@email.com",&nbsp; &nbsp; &nbsp; "phone_number": "0987654321"&nbsp; &nbsp; }&nbsp; &nbsp; }, {&nbsp; &nbsp; "id": 10,&nbsp; &nbsp; "event_id": 13,&nbsp; &nbsp; "details": {&nbsp; &nbsp; &nbsp; "firstname": "John",&nbsp; &nbsp; &nbsp; "lastname": "X Doe",&nbsp; &nbsp; &nbsp; "email_address": "john_x_doe120@xmail.com",&nbsp; &nbsp; &nbsp; "phone_number": "0009876543"&nbsp; &nbsp;}&nbsp; &nbsp;}, {&nbsp; &nbsp;"id": 11,&nbsp; &nbsp;"event_id": 13,&nbsp; &nbsp;"details": {&nbsp; &nbsp; &nbsp;"firstname": "Wari",&nbsp; &nbsp; &nbsp;"lastname": "Gumah",&nbsp; &nbsp; &nbsp;"email_address": "gumahwarihanna@eeee.com",&nbsp; &nbsp; &nbsp;"phone_number": "120029182765"&nbsp; &nbsp; }&nbsp; &nbsp;}]

qq_花开花谢_0

您可以在组件上实现一些逻辑来获取一组字段。它看起来像这样:(我假设项目作为 @Input() 出现在您的组件中,但它可能是另一个来源)@Input() items: Item[];fields: Set<string>;ngOnChanges(changes) {&nbsp; if(!changes.items || !this.items) return;&nbsp; this.fields= new Set(this.items.flatMap(item => Object.keys(item.details)))}然后在模板中<tr *ngFor="let item of items">&nbsp; &nbsp;<td *ngFor="let field of fields">{{item.details[field]}}</td></tr>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript