Mina
Mina

Reputation: 154

Angular Map an observable nested object to another object

I need to map field from sub object in the response JSON to the parent object

I get the following response

{
  "id": 1,
  "name": "file-1",
  "survey": {
    "identifier": 1,
    "displayedValue": survey-1
  }
}

I am trying to map the previous json to this Object

import { Entity } from './entity';

export class File extends Entity {
    name: string;
    survey: Entity['identifier'];
    status: string;
}

Here is Entity class

export class Entity {
    displayedValue: string;
    identifier: string;
}

and here is how I was trying to map it

this.fileService.getFileById(this.fileId).subscribe(data => {
  this.file = data;
});

The file service method

  public getFileById(fileId: string): Observable<File> {
    const getFileByIdURL = environment.backendBaseURL + 'files/' + fileId;
    return this.http.get<File>(getFileByIdURL);
  }

I need the file.survey to contain the survey identifier

Upvotes: 2

Views: 603

Answers (1)

PushpikaWan
PushpikaWan

Reputation: 2525

Simply you can map it like below,

this.fileService.getFileById(this.fileId).subscribe(data => {
  const entity = new Entity();
  entity.displayedValue = data.survey?.displayedValue;
  entity.identifier= data.survey?.identifier;

  this.file = new file();
  this.file.survey = entity;
  this.file.status= 'what u want';
});

Upvotes: 1

Related Questions