-1

I am trying to copy a date property from an object and modify it as shown below, yet each time I try to modify the 'copied' date property, I end up having the object date property modified as well. So was wondering is there a way I can modify the copied date without affecting the date property in the original object? Any help with sample code is highly appreciated. Thanks

A. Object (saved in a taskObject var)

{ name: 'test',
  endDate: Thu Apr 13 2017 18:46:02 GMT+0200 (EET)
}

B. Code:

let currentTaskEndDate = taskObject.endDate; //where taskObject is the object above

//The following line will result in taskObject.endDate to be updated by new date!
currentTaskEndDate.setDate(currentTaskEndDate.getDate() + Number(5)); 
MChan
  • 6,842
  • 27
  • 83
  • 132
  • 1
    use the date you have there to create a new Date and then modify this new date. Objects in javascript are passed by reference. That's why you are seeing this. – yBrodsky Apr 03 '17 at 16:04

3 Answers3

1

Use new Date(taskObject.endDate) to create a copy of the date before you modify it:

const origDate = new Date(2017, 3, 13, 16, 46, 2);

const taskObject = {
  name: 'test',
  endDate: origDate,
};

console.log('taskObject:', taskObject);

// Copy the original Date object before modifying it
const currentTaskEndDateCopy = new Date(taskObject.endDate);
currentTaskEndDateCopy.setDate(currentTaskEndDateCopy.getDate() + 5);

console.log('New Date object:', currentTaskEndDateCopy);
console.log('taskObject (unchanged!):', taskObject);
.as-console-wrapper{min-height:100%}
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
1

As @yBrodsky mentioned use new Date object and modify that one:

For example, you could do something like:

let currentTaskEndDate = new Date(taskObject.endDate);
currentTaskEndDate.setDate(currentTaskEndDate.getDate() + 5);
Gaurav
  • 1,233
  • 14
  • 23
-1

When you copy an object this way, JavaScript passes a reference to the original value.

If you want to copy the value without the reference, you need to do a deep clone. check out _.cloneDeep from lodash

Community
  • 1
  • 1
John Vandivier
  • 2,158
  • 1
  • 17
  • 23