How do I keep a session variable from changing?
Seems like no matter what I do the value of req.session keeps changing.
const copySession - req.session.myObject; const changedCopy = functionThatWantsToChangeTheCopyOnly(copySession);
For some reason even assigning the req.session to a variable, and changing THAT variable, affects the original req.session?
Any ideas why?
Please post your express-session code, middleware and controller routes.
Here's the answer, but please read below to understand why this occurs
const copySession = Object.assign({}, req.session);
I must have originally read your question too quickly at first, wouldn't have asked you to post your code as this is not an express-session problem.
[Copied and pasted from good ole Stackoverflow!] All Credit Goes To: https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change
It is clear that you have some misconceptions of what the statement var tempMyObj = myObj; does. In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj and myObj are both references to the same object.
Here is a simplified illustration that may help you visualize what is happening
// [Object1]<--------- myObj
var tempMyObj = myObj;
// [Object1]<--------- myObj
// ^
// |
// ----------- tempMyObj
As you can see after the assignment, both references are pointing to the same object.
You need to create a copy if you need to modify one and not the other.
// [Object1]<--------- myObj
const tempMyObj = Object.assign({}, myObj);
// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj
@rdalfonso - close ticket?
@rdalfonso - close issue?
Yes I figured it out.