【问题标题】:To display the values of the other JSON using the id [closed]使用 id 显示其他 JSON 的值 [关闭]
【发布时间】:2019-06-03 20:30:49
【问题描述】:

场景:

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

预期结果:

我想根据他们的ID 为特定的contact 显示分配的工作人员name,如下所示:

Stackblitz DEMO

【问题讨论】:

  • @JenyaG 你可以更轻松:) return this.workers.find(w=>w.id==workerId).name
  • 我在控制台中收到此错误:错误错误:无法读取未定义的属性“长度”

标签: json angular typescript angular6


【解决方案1】:

给你

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

【讨论】:

  • 非常好的解决方案!
  • 乐于助人:)
  • 我在控制台中收到此错误:错误错误:无法读取未定义的属性“长度” Stackblitz 链接 stackblitz.com/edit/…
  • @Empty_Soul 您可能忘记初始化变量workerscontacts。检查一下。
  • 我已经初始化了 avery 变量,你可以在 stackblitz lin 本身中看到错误。我在上面的评论中提到了。
【解决方案2】:

您还可以使用Array.prototype.find() 根据id 找到您的工人name。您需要像这样在 .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 演示。我已对您的代码进行了更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-15
    • 2014-07-25
    • 2013-08-10
    • 2021-07-23
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多