PGH
PGH

Reputation: 2204

How access the access the whole object by its id

Here we are having two JSON called 1.contacts and 2.workers contacts json is having id called serviceId is nothing but id of workers. when i try to display contacts i want to display workers relevant to that contacts. Here is the stackblits DEMO

Upvotes: 0

Views: 50

Answers (2)

Karnan Muthukumar
Karnan Muthukumar

Reputation: 1863

Here i have updated stackblitz using sample your data as Array.

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

Code:-

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

Upvotes: 1

molamk
molamk

Reputation: 4116

You can gather the IDs from the contacts IDs in a map by using map then reduce. After that you iterate over your workers and check in the previously generated map if their serviceId is one of the map's keys.

It looks like this

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

Upvotes: 0

Related Questions