1

I'm sure I'm doing something wrong but I'm not sure what it is. I'm expecting the req.query to be the same as it was set at the start but when I log them to the console at the end data and req.query only contain rnd.

var req = {};
req.query = {
    url: 'https://google.com/',
    width: '500',
    height: '190',
    ref: 'http://domain.tld',
    rnd: '9314871930982'
};
var data = req.query;
delete data.width;
delete data.height;
delete data.url;
delete data.ref;

console.log(req.query);
console.log(data);
Alexis Tyler
  • 1,394
  • 6
  • 30
  • 48
  • 2
    possible duplicate of [How to copy JavaScript object to new variable NOT by reference?](http://stackoverflow.com/questions/18359093/how-to-copy-javascript-object-to-new-variable-not-by-reference) – Alexis Tyler Mar 01 '15 at 06:10

1 Answers1

1

When you do

var data = req.query;

you are making data refer the same object which req.query also refers.

+-----------------+                     +----------------------------+
|      data       |====================>| url:'https://google.com/'  |
+-----------------+                     | width: '500'               |
                                        | height: '190'              |
+-----------------+                     | ref: 'http://domain.tld'   |
|    req.query    |====================>| rnd: '9314871930982'       |
+-----------------+                     +----------------------------+

So, any change to the object, through either data or req.query, will be reflected on all the other references as well. Its more like accessing the same object with two different names.

With this understanding, if we look at your code, when you delete things from data, you are actually deleting from the object referred by req.query.

If you don't want this to happen, you need to clone req.query with any of the methods mentioned in this thread.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497