简体   繁体   中英

Modify api response in service of angular

I am trying to modify the response return by API request. Right now I am getting the response as

[
   {
       name: "Afghanistan"
   }, 
   {
       name: "Åland Islands"
   }
]

I want to modify it to:

[
   {
        name: "Afghanistan",
        name1: "Afghanistan",
        name2: "Afghanistan"
    },
    {
        name: "Åland Islands",
        name1: "Åland Islands",
        name2: "Åland Islands"
    }
]

I am trying to copy name field and create new fields eg: name1, name2 in same object . Here is working project https://stackblitz.com/edit/angular-8bzcdp can any one help

You can change your method to:

  getRecords() {
    return this.http.get('https://restcountries.eu/rest/v2/all').pipe(
      map((res: any[]) => {
        const data = res.map(obj => ({
          name: obj.name,
          name1: obj.name,
          name2: obj.name
        }));
        return data;
      })
    );
  }

Here on the resulting response array ( res[] ) we map each element into a json object based on your criteria and return the newly created json object.

You can modify your response after you subscribe

this.service.getRecords().subscribe(res => {
  console.log(res);
  console.log(res.reduce((a, c) => Object.assign(a, c), {}));
});

for details please visit the updated stackblitz link

https://stackblitz.com/edit/angular-nwwef1?file=src/app/app.component.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM