迭代Angular2中json对象的键

时间:2018-04-13 09:09:40

标签: angular

我收到这样的JSON响应: -

{
  "status": 1,
  "message": "Data found",
  "list": [
    {
      "id": "1",
      "title": "First Data"
    },
    {
      "id": "2",
      "title": "Second Data"
    }
  ],
  "total": 3,
  "current_page": "1",
  "error": 0
}

在组件文件中,我存储list obj,如下所示: -

viewPage(page,per_page){  
  this._adminPage.fetchAdminPageData(page, per_page).subscribe(
      data => {
            this.list = data.list;
            this.total_item = data.total;
            this.current_page = data.current_page;
            this.arrayOfKeys = Object.keys(this.list);
            //this.setPage(1);
          },
      err => {
            console.log(err)
          },
      () => {}
    ); 
  this.status = true;       
}

使用this.arrayOfKeys = Object.keys(this.list);我正在获取list的密钥。

当我在html {{arrayOfKeys}}中打印时,我会收到这样的数据0,1

我想遍历list [0]的键,并在表头中显示每个键的名称。有点链接: -

<thead>
  <tr>
   <th *ngFor='let key of arrayOfKeys'>[here goes the name of the key ie. id/title/etc]</th>
  </tr>
</thead>

这意味着,如果我的密钥是 id &amp; 标题然后表格标题会显示 ID 标题。如果我的密钥是 f_name &amp; l_name ,然后表格标题会显示 f_name l_name

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

如果每个数组元素具有相同的no键,则可以使用this.arrayOfKeys=Object.keys(list[0]);。如果使用Object.keys(list);,它将只为您提供数组索引。您可以查看以下代码 -

viewPage(page,per_page){  
  this._adminPage.fetchAdminPageData(page, per_page).subscribe(
      data => {
            this.list = data.list;
            this.total_item = data.total;
            this.current_page = data.current_page;
            this.arrayOfKeys=Object.keys(list[0]); //["id", "title"]
            //this.setPage(1);
          },
      err => {
            console.log(err)
          },
      () => {}
    ); 
  this.status = true;       
}

然后在HTML

中使用它
<thead>
  <tr>
   <th *ngFor='let key of arrayOfKeys'>{{key}}</th>
  </tr>
</thead>

答案 1 :(得分:1)

如果所有对象的键都相同并且存在,则可以使用:

const keys = Object.keys(data.list[0]);

如果没有,您可以聚合所有对象的键,例如使用itermediate Set

const data = {
  "status": 1,
  "message": "Data found",
  "list": [{
      "id": "1",
      "title": "First Data"
    },
    {
      "id": "2",
      "title": "Second Data"
    }
  ],
  "total": 3,
  "current_page": "1",
  "error": 0
};

const keys = Array.from(data.list.reduce((a, v) => {
  Object.keys(v).forEach(k => a.add(k));
  return a;
}, new Set()));

console.log(keys);

答案 2 :(得分:0)

Object.keys()方法从组件展示到您的模板:

public objKeys = Object.keys;

所以你可以迭代键:

<div *ngFor="let key of objKeys(yourObject)">{{key}}</div>