I need to copy moment
to a new variable without references.
let momentDate = moment('2018-01-01', 'YYYY-MM-DD');
// I need to create a full clone of moment here
// Tried:
// -- let copy = {...moment}
// -- let copy = new(moment)
// -- let copy = clone(moment) //
// -- let copy = Object.assign({}, moment)
let momentCopy = /*new*/ moment;
momentCopy.fn.xFormat = function() {
return this.format('[new-format-fn::]' + 'YYYY-MM-DD')
}
// expected Error:momentDate.xFormat is not a function
// but xFormat applied to momentDate
log(momentDate.xFormat());
log(momentCopy().xFormat())
Can anyone help me?
jsfiddle example
I need to copy moment
to a new variable without references.
let momentDate = moment('2018-01-01', 'YYYY-MM-DD');
// I need to create a full clone of moment here
// Tried:
// -- let copy = {...moment}
// -- let copy = new(moment)
// -- let copy = clone(moment) // https://www.npmjs./package/clone
// -- let copy = Object.assign({}, moment)
let momentCopy = /*new*/ moment;
momentCopy.fn.xFormat = function() {
return this.format('[new-format-fn::]' + 'YYYY-MM-DD')
}
// expected Error:momentDate.xFormat is not a function
// but xFormat applied to momentDate
log(momentDate.xFormat());
log(momentCopy().xFormat())
Can anyone help me?
jsfiddle example
Share Improve this question asked Jan 14, 2019 at 6:50 talkhabitalkhabi 2,7593 gold badges22 silver badges29 bronze badges 03 Answers
Reset to default 4Use moment(Moment);
to clone a moment object.
And moment.fn
is moment prototype. If you want to add custom method to copied object, you can set as momentCopy.xFormat = function(){}
let momentDate = moment('2018-01-01', 'YYYY-MM-DD');
let momentCopy = moment(momentDate);
momentCopy.xFormat = function() {
return this.format('[new-format-fn::]' + 'YYYY-MM-DD')
}
console.log(momentCopy.xFormat())
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.22.2/moment.js"></script>
From the docs,
All moments are mutable. If you want a clone of a moment, you can do so implicitly or explicitly. Calling
moment()
on a moment will clone it.
So just provide it back to moment( momentObj )
Import "cloneDeep" from "Lodash" and then
let momentCopy = cloneDeep(moment);
should work for you.