skip to Main Content

below is part of my code

    this.diaryToEdit.diaryStatus.statusName = updatedDiary.diaryStatus.statusName;
    this.diaryToEdit.diaryStatus.statusId = updatedDiary.diaryStatus.statusId;
    this.diaryToEdit.actioDate = new Date(updatedDiary.actioDate);
    this.diaryToEdit.actionText = updatedDiary.actionText;
    this.diaryToEdit.diaryType = updatedDiary.diaryType;

Similary there are more properties which needs to be updated in this.diaryToEdit with updatedDiary values. Instead of writing like above, is there any better way to format code. Please suggest.

2

Answers


  1. you could use spread syntax.

    this.diaryToEdit = {...this.diaryToEdit, diaryType: updatedDiary.diaryType, actionText: updatedDiary.actionText}
    

    note that this will create a new object with modified values.

    Login or Signup to reply.
  2. It depends on your needs, i.e. if you want to clone the information first, or if you only need to keep some data contained in "updatedDiary", etc…

    If it’s okay (don’t clone and keep any info) I’d probably re-write it like this:

    this.diaryToEdit = {
        ...updatedDiary, 
        actioDate: new Date(updatedDiary.actioDate)
    }
    

    Otherwise it is better to create a clean copy:

    let updatedDiaryClone = structuredClone(updatedDiary);
    this.diaryToEdit = {
        diaryStatus: updatedDiaryClone.diaryStatus,
        actioDate: new Date(updatedDiaryClone.actioDate),
        actionText: updatedDiaryClone.actionText,
        diaryType: updatedDiaryClone.diaryType
    }
    

    But I repeat, it depends on your needs and possibly on the type of data you are cloning.

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