Are there any aspects of assigning an object to be restructured by reference?

I have a program that increments requests in a session cookie and prints them to the console. At first I tried to figure out how I can save this data. After entering a couple of places, I realized that the data was saved / changed, despite the fact that I have a separate variable to hold what I thought was a temporary version of the req member object.

This is the code that made me realize that the actual object was changed when I incremented the variable that I assigned to it:

recordRequest(req) { const { ip } = req.info; const { requestsPerSecond } = req.session; if (req.originalUrl.split('/').filter(Boolean)[0] == 'www.example.com') { requestsPerSecond[ip] = requestsPerSecond[ip] + 1 || 1; } console.log(req.session.requestsPerSecond); } 

I cannot find in the documents here or in Mozilla whether this is the intended behavior, whether it is the result of using a constant (where you can mutate member variables), or there are some kind of strange error. I also had problems reproducing this example on a smaller scale, but I was convinced that nothing is happening or is not coming out of the function that affects this piece of code.

This is not a violation of my code or anything else (it makes my life easier), but I want to understand why this is happening!

+5
source share
2 answers

By default, I would deform an object that works essentially the same as regular destinations. Consider:

 const req = {session: {requestsPerSecond: {"0.0.0.0": "foo"}}}; const requestsPerSecond = req.session.requestsPerSecond; // updates to `requestsPerSecond` will also update `req`. 

I'm not sure if you can use destructuring to break the assignment, so you have to use the usual tactic:

 const requestsPerSecond = Object.assign({}, req.session.requestsPerSecond); 
+4
source

From MDN:

Destructuring destination syntax is a JavaScript expression that allows you to retrieve data from arrays or objects into separate variables.

If this data is an object reference, this object reference will be copied to a new variable or in your case constant.

Minimal example:

 const orig = { foo: { bar: 1 } } const { foo } = orig; console.log(foo.bar); // 1 console.log(orig.foo.bar); // 1 foo.bar++; console.log(foo.bar); // 2 console.log(orig.foo.bar); // 2 
+1
source

All Articles