To display the values of the other JSON using the id

Viewed 79

SCENARIO:

I have 2 JSON files called contacts & workers:

contacts

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

workers

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

I am displaying contacts like this:

enter image description here

EXPECTED RESULT :

I want to display assigned workers name for particular contact based on their ID like this:

enter image description here

Stackblitz DEMO

2 Answers

Here you go

<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>

You could also use Array.prototype.find() to find your worker name based on the id. You need to create function inside of your .ts file like this

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

    return obj ? obj.name : '';
 }

And your component file is like this

<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>

You could check with this working stackblitz demo. I have made changes in your code.

Related