Changing Date Copied From An Object
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
Solution 1:
As @yBrodsky mentioned use new Date
object and modify that one:
For example, you could do something like:
let currentTaskEndDate = newDate(taskObject.endDate);
currentTaskEndDate.setDate(currentTaskEndDate.getDate() + 5);
Solution 2:
Use new Date(taskObject.endDate)
to create a copy of the date before you modify it:
const origDate = newDate(2017, 3, 13, 16, 46, 2);
const taskObject = {
name: 'test',
endDate: origDate,
};
console.log('taskObject:', taskObject);
// Copy the original Date object before modifying itconst currentTaskEndDateCopy = newDate(taskObject.endDate);
currentTaskEndDateCopy.setDate(currentTaskEndDateCopy.getDate() + 5);
console.log('New Date object:', currentTaskEndDateCopy);
console.log('taskObject (unchanged!):', taskObject);
.as-console-wrapper{min-height:100%}
Solution 3:
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
Post a Comment for "Changing Date Copied From An Object"