使用id显示其他JSON的值

时间:2019-01-09 05:36:03

标签: json angular typescript angular6

场景:

我有2个JSON文件,分别名为contactsworkers

联系人

  [
     {
      "name": "Jhon Doe",
      "gender": "Male",
      "workers": [
        "e39f9302-77b3-4c52-a858-adb67651ce86",
        "38688c41-8fda-41d7-b0f5-c37dce3f5374"
       ]
     },
     {
      "name": "Peter Parker",
      "gender": "Male",
      "workers": [
         "e39f9302-77b3-4c52-a858-adb67651ce86",
         "40665c50-ff74-4e81-b968-e127bdf1fe28"
        ]
     },
     {
      "name": "Mark Wood",
      "gender": "Male",
      "workers": [
          "ed780d15-428b-4bcd-8a91-bacae8b0b72e"
         ]
     },
     {
      "name": "Mary Jane",
      "gender": "Female",
      "workers": [
         "40665c50-ff74-4e81-b968-e127bdf1fe28",
         "ed780d15-428b-4bcd-8a91-bacae8b0b72e"
       ]
     }
]

工人

  [
   {
     "id": "e39f9302-77b3-4c52-a858-adb67651ce86",
     "name": "Alfy Odhams"
   },
   {
     "id": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
     "name": "Allsun Suttle"
   },
   {
     "id": "ed780d15-428b-4bcd-8a91-bacae8b0b72e",
     "name": "Alvinia Ettritch"
   },
   {
     "id": "40665c50-ff74-4e81-b968-e127bdf1fe28",
     "name": "Ambrosi Lindenstrauss"
   }
 ]

我正在这样显示contacts

enter image description here

预期结果:

我想基于他们的name显示特定工人contact的已分配工人ID,如下所示:

enter image description here

Stackblitz DEMO

2 个答案:

答案 0 :(得分:4)

你在这里

<tr>
    <td>Assigned Workers</td>
    <td>
        <div *ngFor="let cWorker of contact.workers">
            <div *ngFor="let worker of workers" [hidden]="cWorker!=worker.id">
              {{worker.name}}
            </div>
        </div>
    </td>
</tr>

答案 1 :(得分:2)

您还可以使用Array.prototype.find()根据name查找工作人员id。您需要像这样在.ts文件内部创建函数

 findWorkerName(wid) {
    let obj = this.workers.find(({ id }) => id = wid)

    return obj ? obj.name : '';
 }

您的组件文件就是这样

<h4>Contacts</h4>
<div class="cust-detail" *ngFor="let contact of contacts">
    <tr>
        <td>Name</td>
        <td>{{contact.name }}</td>
    </tr>
    <tr>
        <td>Gender</td>
        <td>{{contact.gender}} </td>
    </tr>
    <tr>
        <td>Assigned Workers</td>
        <td>
            <span *ngFor="let id of contact.workers let i = index">
            {{findWorkerName(id)}} {{i<contact.workers.length-1?',':''}}
          </span>
        </td>
      </tr>
             <hr>
  </div>

您可以查看此有效的stackblitz演示。我已经更改了您的代码。