[英]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.我有这个 DTO,当我尝试将其转换为 object 时,它不会转换为我想要的方式。 Value converted to object but field name remains the same.
值转换为 object 但字段名称保持不变。
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
我有这个 DTO,想把它转换成这样的 object
{
'name': 'string',
'url': 'string',
'category': 'legal',
'page_view': {
stand_alone: false,
},
}
If you have the dto instance, and you want to covert it to an object.如果您有 dto 实例,并且想要将其转换为 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: Output:
{ page_view: { stand_alone: false } }
So I think you actually have a plain object from http request.所以我认为你实际上有一个来自 http 请求的普通 object 。 And your framework like Nestjs convert the request object to the dto instance.
并且您的框架(例如 Nestjs)将请求 object 转换为 dto 实例。 This process is
plainToInstance
, not instanceToPlain
.这个过程是
plainToInstance
,而不是instanceToPlain
。 You can try swapping page_view
and stand_alone
like the following code:您可以尝试像以下代码一样交换
page_view
和stand_alone
:
class CreatePageGroupsDto {
@Expose({ name: 'stand_alone' })
@Transform(({ value = false }) => {
const pageView = { stand_alone: value };
return pageView;
})
page_view?: boolean;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.