class-transformer icon indicating copy to clipboard operation
class-transformer copied to clipboard

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

Open PerryFinn opened this issue 2 years ago • 5 comments

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.

PerryFinn avatar Feb 01 '23 16:02 PerryFinn

Hello @Chen-913,

you can try the exposeUnsetFields: false option like: console.log(plainToInstance(User, fromPlainUser, { excludeExtraneousValues: true, exposeUnsetFields: false}));

diffy0712 avatar May 22 '24 21:05 diffy0712

@diffy0712 Hello there. This is not working. All fields are undefined=(

reedoso avatar Jun 07 '24 14:06 reedoso

Are there any plans to fix this issue?🧐

PerryFinn avatar Jul 29 '24 16:07 PerryFinn

I would be interested in contributing to resolve this, as I genuinely need this feature, or we'll need to move on to another package. @NoNameProvided

colemvnio avatar Oct 13 '24 22:10 colemvnio

Is there a plan to implement this feature?

yurikong avatar Mar 25 '25 04:03 yurikong