Search code examples
jsonangulardictionarypiperesponse

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


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": "Sincere@april.biz"
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv"
  }
] 

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


Solution

  • 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}))
      })
     )
    }