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
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.
Given that you have few changes, you can just clone the whole object and then make simple modifications.
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:
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.