Saranya Garimella
Saranya Garimella

Reputation: 542

How to modify the data response from a service call

I am looking for formatting the data I receive from the service call. The data I receive from the service call is of the format:

{
    path: "Protocols/abc Protocols",
    protocols: [
    {
    id: {
    name: "Dynamic abc",
    path1: "Protocols/abc Protocols/abc",
    path2: "Protocols/abc Protocols/abc2",
    path3: "Protocols/abc Protocols/abc3",
    summary: "Provides abc..... "
    }
    },
    {
    id: {
    name: "Dynamic def",
    path1: "Protocols/def Protocols/def ",
    path2: "Protocols/def Protocols/def2",
    path3: "Protocols/def Protocols/def3",
    summary: "Provides def..... "
    }
    },
    {
    id: {
    name: "Dynamic efg",
    path1: "Protocols/def Protocols/efg ",
    path2: "Protocols/def Protocols/efg2",
    path3: "Protocols/def Protocols/efg3",
    }
    }
    ]
    }

For this data, my data model is in the format:

path: string;
  protocols: [
  {
    id: 
    {
    name: string,
    path1: string,
    path2: string,
    path3: string,
    }
  }
  ]

I would like to remove the 'id' part of the response make the data model in the format:

 path: string;
          protocols: [
            {
              name: string,
              path1: string,
              path2: string,
              path3: string,
            },
            {
              name: string,
              path1: string,
              path2: string,
              path3: string,
            }
          ]

I am trying the standard approach of creating an array and pushing everything inside each of the id{} to an array.

for (let i = 0; i < result.protocols.length; i++) {
                finalResult.push(result.protocols[i].id);
    }

Is there a better way to achieve it? I am an amateur Angular6 developer. Need help?

Upvotes: 0

Views: 40

Answers (1)

zfrisch
zfrisch

Reputation: 8660

You can map over the protocols array and simply return the lower nested object instead of the higher level that contains id

data.protocols = data.protocols.map(i => i.id);

var data={path:"Protocols/abc Protocols",protocols:[{id:{name:"Dynamic abc",path1:"Protocols/abc Protocols/abc",path2:"Protocols/abc Protocols/abc2",path3:"Protocols/abc Protocols/abc3",summary:"Provides abc..... "}},{id:{name:"Dynamic def",path1:"Protocols/def Protocols/def ",path2:"Protocols/def Protocols/def2",path3:"Protocols/def Protocols/def3",summary:"Provides def..... "}},{id:{name:"Dynamic efg",path1:"Protocols/def Protocols/efg ",path2:"Protocols/def Protocols/efg2",path3:"Protocols/def Protocols/efg3"}}]};
data.protocols = data.protocols.map(i => i.id);
console.log(data);

Upvotes: 1

Related Questions