skip to Main Content

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;

3

Answers


  1. You should use destructuring assignment to rename a property. There is no shorthand for applying a function to a property value though; you have to do that manually.

    const {id: client_id, ...rest} = originalObject;
    const res: NewDto = {...rest, client_id, client_created_at: 
                              convertToDate(originalObject.created_at)};
    
    Login or Signup to reply.
  2. 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;
    }
    
    Login or Signup to reply.
  3. The code you provided is close to achieving the desired transformation, but there are a few issues that need to be addressed. Here’s an updated version of the code that should work:

    const newObject: NewDto = {
      client_id: originalObject.id as number,
      ...originalObject,
      client_created_at: new Date(originalObject.created_at as number),
    };
    

    In this code, we explicitly specify the type of newObject as NewDto to ensure type safety. Then, we assign the client_id field by casting originalObject.id to number since originalObject.id is of type unknown. Next, we use the spread operator (…) to copy all the fields from originalObject to newObject.

    Finally, we assign the client_created_at field by converting the millisecond timestamp to a Date object using the Date constructor.

    Make sure you have the necessary imports and that the NewDto class is defined properly. With this code, you should be able to transform your original object into the new object with the desired field renaming and conversion to a Date object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search