Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda