2

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

1 Answer 1

1

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';
});
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick answer. But what if I have multiple nested objects like the survey is there a more generic way to do them all automatically instead of doing it manually. Like in my code I wrote "survey: Entity['Identifier']" like I am telling him it's an entity object but I only need it's Identifier
ok. Then u can use Interface or Types instead of classes and use ES6 Destructuring like mechanism by changing attribute to provide it in proper way
Would be a lot if I ask for an example. Thanks again

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.