如何通过ID访问整个对象

时间:2019-02-07 11:36:15

标签: json angular

在这里,我们有两个名为 1.contacts和2.workers 的JSON。json的ID为 serviceId ,不过是 workers的身份。当我尝试显示联系人时,我想显示与该联系人相关的工作人员。这是 DEMO

2 个答案:

答案 0 :(得分:1)

在这里,我已将样本数据用作数组来更新stackblitz。

https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-ujzzx1

代码:-

let finalResult:any[]=[];
    for(let contact of this.contacts){
      if(contact.serviceId){
        finalResult.push(this.workers.filter(o=>o.id == contact.serviceId));
      }
    }

    console.log("finalResult",finalResult);

答案 1 :(得分:0)

您可以先使用map然后使用reduce从地图的联系人ID 中收集ID。之后,您遍历工作人员,并检查先前生成的地图是否他们的serviceId是地图的键之一。

看起来像这样

const contacts = [{
    "name": "Jhon Doe",
    "gender": "Male",
    "serviceId":  "e39f9302-77b3-4c52-a858-adb67651ce86",
  },
  {
    "name": "Peter Parker",
    "gender": "Male",
    "serviceId":  "e39f9302-77b3-4c52-a858-adb67651ce86",
  },
  {
    "name": "Mark Wood",
    "gender": "Male",
       "serviceId":  "38688c41-8fda-41d7-b0f5-c37dce3f5374",
  },
  {
    "name": "Mary Jane",
    "gender": "Female",
    "serviceId":  "38688c41-8fda-41d7-b0f5-c37dce3f5374",
  }
];

const 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"
    }
];

const contactsIDs = contacts.map(c => c.serviceId).reduce((acc, curr) => {
  acc[curr] = true;
  return acc;
}, {});

const filteredWorkers = workers.filter(w => w.id in contactsIDs);
console.log(filteredWorkers);