Search code examples
javascripttypescriptnestjs

In javascript, how to rename few properties of a huge object


I have an object with 120+ fields, and I am looking for a way to transform the object into a new object.

The new object is mostly identical to the original, except few fields are renamed and few fields are converted to Date object from milliseconds time.

Original Object: type: Record<string, unknown> Sample Value:

{
  "id":12,
  ...
  "created_at":1577999390226497 // Time in milliseconds
}

New Object type: Custom Object

export class NewDto {
  client_id: number;
  ...
  client_created_at: Date;
  
}

I tried using slicing but it's not working. Sample code:

  const newObject = {
    ...originalObject,
    id: client_id,
    created_at: convertToDate(created_at)
  } as NewDto;

Solution

  • Given that you have few changes, you can just clone the whole object and then make simple modifications.

    function transformed(orig) {
        // Clone the original.
        let cloned={...orig};
        // Add/Overwrite any changes
        cloned.client_id=orig.id;
        cloned.created_at=new Date(orig.created_at/1000);
        // Remove any renamed fields
        delete cloned.id;
        return cloned;
    }