从Angular中的json获取键和值

时间:2019-04-27 16:52:37

标签: json angular

我需要从json获取值(来自合并的MySQL表)。

我已经尝试了上一个主题中的几种解决方案,但是没有一个对我有用。

access key and value of object using *ngFor

我的JSON格式是:

[
   {
      "idemployee":1,
      "name":"Ernest",
      "surename":"Pająk",
      "role":"Obsługa Baru",
      "employeehours":[
         {
            "idemployeehours":1,
            "date":"2019-01-10T23:00:00.000+0000",
            "quantity":8.0
         }
      ]
   }
]

我得到的是“键:0和值:”(以上Pardeep Jain主题的答案)

编辑: 这是我的代码:

<div *ngFor="let item of employee| keyvalue">
Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>

员工来自Angular组件,并提供了提到的JSON。问题是从“员工工时”(例如数量)中获取嵌套值

2 个答案:

答案 0 :(得分:0)

如果在数组对象上运行keyValue管道,则将键作为数组中值的索引,因此为什么需要嵌套ngFor才能在数组的值上运行keyvalue管道

<div *ngFor="let item of employee">
    <div *ngFor="let emp of item |keyvalue "> 
        Key: <b>{{emp.key}}</b> and Value: <b>{{emp.value}}</b>
  </div>
</div>

demo

已更新!

如果您要支持员工小时的键值,其中值是数组的最佳情况,请在此处创建一个组件来执行所有这些操作,并使用该组件来呈现新值,例如递归

组件

export class RenderComponent  {

  @Input() items = [];

  isArray(value) {
    return value instanceof Array
  }
}

模板

<div *ngFor="let item of items">
    <div *ngFor="let obj of item | keyvalue " class="well"> 
        Key: <b>{{obj.key}}</b> and Value: <b>{{obj.value}}</b>

        <ng-container *ngIf="isArray(obj.value)">
            <render [items]="obj.value"></render>
        </ng-container>

  </div>
</div>

demo

答案 1 :(得分:0)

您不需要keyvalue管道。 employeehours是一个数组,因此您只需要嵌套的*ngFor即可,因此示例将数据存储在employees数组中:

<div *ngFor="let emp of employees">
  <p>Name: {{emp.name}} {{emp.surename}}</p>
  <div *ngFor="let hour of emp.employeehours">
    <p>Date: {{hour.date | date: 'shortDate'}}</p>
    <p>Quantity: {{hour.quantity}}</p>
  </div>
</div>

DEMO

相关问题