Skip to content

question: How can I convert some optional parameters defined in the model without excluding the attributes not defined in the model? #1445

Open
@PerryFinn

Description

@PerryFinn

I was trying to...

I hope that when some parameters of the Model are optional, I can automatically remove some parameters that are not passed in, instead of changing its value to undefined.

As the example in the document:

import { Expose, plainToClass } from 'class-transformer';

// Assume that these fields are optional
class User {
  @Expose() id?: number;
  @Expose() firstName?: string;
  @Expose() lastName?: string;
}

const fromPlainUser = {
  unkownProp: 'hello there',
  firstName: 'Umed',
  lastName: 'Khudoiberdiev',
};

console.log(plainToInstance(User, fromPlainUser, { excludeExtraneousValues: true }));

// User {
//   id: undefined,
//   firstName: 'Umed',
//   lastName: 'Khudoiberdiev'
// }

The problem:

In the case of no id transfer, it is converted to undefined by default, which I don't want to do. The effect I want is that if I don't transfer the id field, the converted object will not have the id field.

I know that fields with undefined can be removed by some other methods.
for example:

console.log(JSON.parse(JSON.strigify(transformObj)));
// User {
//   firstName: 'Umed',
//   lastName: 'Khudoiberdiev'
// }

I want to ask whether this tool provides such functions or options to call to achieve this effect. I can't find it in the document.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions