Home > database >  How to return specific fields from a JSON object array in angular http service as response
How to return specific fields from a JSON object array in angular http service as response

Time:09-23

My Interface is like this:

export interface User {
    id: number;
    name: string;
}

Response i received from api is:

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "[email protected]"
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "[email protected]"
  }
] 

I wish to extract only id and name fields and return as response

[
  {
    "id": 1,
    "name": "Leanne Graham"
  },
  {
    "id": 2,
    "name": "Ervin Howell"
  }
] 
getdata(): Observable<User[]>{
   return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users').pipe(
     map((data: User[])=> {
       //how to extract id and name here
     })
   )
} 

I need to return only id and name fields from the whole api response. How can i achieve that using map or any other techniques inside service, Please guide me

CodePudding user response:

getdata(): Observable<User[]>{ 
 return this.http.get<User[]>('https://jsonplaceholder.typicode.com/users').pipe(
  map((data: User[])=> {
   //  just map the data 
   return data.map(u => ({id: u.id, name: u.name}))
  })
 )
} 
  • Related