Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
How to transform field name using class transformer

I have this DTO and when I try to convert it to an object it doesn't convert to the way I want. Value converted to object but field name remains the same.

export class CreatePageGroupsDto {

@IsString()
@Expose()
name: string;


@IsString()
@Expose()
url: string;


@IsEnum(CategoryEnum)
@Expose()
category: CategoryEnum;


@Expose({ name: 'page_view' })
@Transform(({
    value = false,
}, ) => {
    const pageView: PageView = { stand_alone: value };
    return pageView;
} )

stand_alone?: boolean;
}

I have this DTO and want to convert it to an object like this

{
        'name': 'string',
        'url': 'string',
        'category': 'legal',
        'page_view': {
            stand_alone: false,
        },
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you have the dto instance, and you want to covert it to an object. Your code is right.

import { Expose, instanceToPlain, Transform } from 'class-transformer';

class CreatePageGroupsDto {
  @Expose({ name: 'page_view' })
  @Transform(({ value = false }) => {
    const pageView = { stand_alone: value };
    return pageView;
  })
  stand_alone?: boolean;
}

const dto = new CreatePageGroupsDto();
dto.stand_alone = false;

console.log(instanceToPlain(dto));

Output:

{ page_view: { stand_alone: false } }

So I think you actually have a plain object from http request. And your framework like Nestjs convert the request object to the dto instance. This process is plainToInstance, not instanceToPlain. You can try swapping page_view and stand_alone like the following code:

class CreatePageGroupsDto {
  @Expose({ name: 'stand_alone' })
  @Transform(({ value = false }) => {
    const pageView = { stand_alone: value };
    return pageView;
  })
  page_view?: boolean;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!