根据ID访问对象属性

时间:2019-02-08 04:42:40

标签: angular typescript angular6

我有两个名为teacherssessions的api。

teachers JSON 文件:

   [
      {
        "teacherName": "Binky Alderwick",
        "id": "01"
      },
      {
        "teacherName": "Basilio Gregg",
        "id": "02"
      },
      {
        "teacherName": "Binky Alderwick",
        "id": "03"
      },
      {
        "teacherName": "Cole Moxom",
        "id": "04"
      }
    ] 

sessions JSON 文件:

[
    {
        "id":"001",
        "sessionName": "Chemistry",
        "notes": "Chemistry is the study of matter, its properties",
        "teacherId": "01"<==========
    },
    {
        "id":"002",
        "sessionName": "Physics",
        "notes": "Physics is the natural science that studies matter and its motion ",
        "teacherId": "03"
    },
    {
        "id":"003",
        "sessionName": "Maths",
        "notes": "Mathematics includes the study of such topics as quantity",
        "teacherId": "01"<=========

    },
    {
        "id":"004",
        "sessionName": "Biology",
       "notes": "Biology is the natural science that studies life and living organisms",
        "teacherId": "04"
    }
]

现在,我正在这样显示模板中的所有教师:

enter image description here

会话 JSON中,我提到了 teacherID ,我想显示基于特定老师sessionsteachersID上。

对于以前的会话,(化学与数学)包含 teacherID 为(01),所以我想在老师1(i,e Binky)下显示这两个会话(化学与数学) Alderwick)

enter image description here

我应该基于session获取teacherId对象的所有属性。

Stackblitz DEMO

1 个答案:

答案 0 :(得分:2)

您可以创建一个函数,该函数返回特定老师的会话数组。

示例:app.component.ts

getSessionForTeacher(teacherId) {
    return this.sessions ? this.sessions.filter(x => x.teacherId === teacherId) : [];
}

HTML:

<h4>Teachers</h4>
<div class="cust-detail" *ngFor="let teacher of teachers">
    <tr>
        <td>Name</td>
        <td>{{teacher.teacherName }}</td>
    </tr>
    <tr>
        <td>Sessions</td>
        <td><br>
      <div *ngFor="let item of getSessionForTeacher(teacher.id)">
      <h2>{{item.sessionName}}</h2>
      <p>{{item.notes}}</p>
      </div>
    </td>
    </tr>   
    <hr>
</div>

StackBlitz这是您问题的完整说明。