2

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

4
  • What have you tried so far? Commented Jul 30, 2019 at 17:47
  • I have tried the code which is given at a link above Commented Jul 30, 2019 at 17:49
  • data.map(({ name }) => ({ name, name1: name, name2: name }) Commented Jul 30, 2019 at 17:54
  • thanks @MoxxiManagarm Commented Jul 30, 2019 at 18:03

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.