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

时间:2019-09-12 12:02:36

标签: javascript arrays json 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来访问我什至不知道的属性。 是什至可以尝试做的事情,如果可以,请告诉我如何做。

谢谢!。

2 个答案:

答案 0 :(得分:1)

您可以使用keyvalue pipe访问详细信息对象,将对象键/值作为内部for循环进行迭代。

HTML:

  <table>
     <tr>              
       <th>Firstname</th>
       <th>lastname</th>
       <th>email_address</th>
       <th>phone_number</th>
     </tr>
     <tr *ngFor="let listItem of yourList" >
       <td *ngFor="let innerItem of listItem.details | keyvalue"> 
         {{innerItem.value}
       </td>
     </tr>
   </table>

填充列表

   yourList = [{
    "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"
    }
   }]

答案 1 :(得分:-1)

您可以在组件上实现一些逻辑以获取一组字段。它将看起来像这样:(我假设项目以@Input()的形式出现在您的组件中,但它可能是另一个来源)

CREATE OR REPLACE PROCEDURE ADD_CUST_TO_DB (pcustid number, pcustname varchar2) AS
err_range EXCEPTION;
BEGIN
    if pcustid < 1 OR pcustid > 499 THEN
        RAISE err_range;
    ELSE
        INSERT INTO CUSTOMER (CUSTID, CUSTNAME, SALES_YTD, STATUS) VALUES (pcustid, pcustname, 0, 'OK');
    END IF;
EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        dbms_output.put_line('ORA-20001:ERROR:DUPLICATE CUSTOMER ID');
        RAISE; --add this
    WHEN err_range THEN
        dbms_output.put_line('ORA-20002:ERROR:CUSTOMER ID OUT OF RANGE');
        RAISE; --add this
    WHEN OTHERS THEN
        dbms_output.put_line(SQLERRM);
        dbms_output.put_line(SQLCODE);
        RAISE; --add this
END;
/

然后在模板中

@Input() items: Item[];
fields: Set<string>;
ngOnChanges(changes) {
  if(!changes.items || !this.items) return;
  this.fields= new Set(this.items.flatMap(item => Object.keys(item.details)))
}