Search code examples
javascripttypescriptangular7

Extract only required variable from Response - Angular 7


I have the following interface

interface Employee{name?:string;id?:string;role?:string;}

I Have a Response like this

{
   "name": "John",
   "id": "ID77777",
   "role": "Engineer",
   "bloodType": "O+ve",
   "placeOfDeployment": "NY"
}

I want to extract only the member variables of Interface.So after i am done with the mapping i should get

{
   "name": "John",
   "id": "ID77777",
   "role": "Engineer"
}

Solution

  • You can use lodash which has pick function or here's vanilla js with same result.

    const res = {"name": "John","id": "ID77777","role": "Engineer","bloodType": "O+ve","placeOfDeployment": "NY"};
    
    const user = ["name", "id", "role"].reduce((acc, key) => {
      acc[key] = res[key];
      return acc;
    }, {})
    

    Note: handle case where res has missing keys.