Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript delete keyword not working properly

Tags:

javascript

This is really weird I think, I have this json being sent through http.

{
   "foo":"bar",
   "foo2":"bar2",
   "name":{
       "firstName":"Joff",
       "middleName":"Ramirez",
       "lastName":"Tiquez"
   }
}

On the server I was performing these commands:

var data = req.body; // the json from http
console.log('data', data); // the data now has the req.body's value 
delete data.name; // <-- here's the delete
console.log('data', data); // the name object will obviously be deleted
console.log('req.body', req.body); // the name on the req.body was deleted too. Wtf?

So when I tried to use the req.body.name on the other parts of my program, the name is now gone. Is that how delete is supposed to work?

like image 591
CENT1PEDE Avatar asked Jun 14 '26 21:06

CENT1PEDE


1 Answers

var data = JSON.parse(JSON.stringify(req.body));
delete data.name; // <-- here's the delete

Now when you do a

console.log('req.body', req.body); // This won't be deleted. 

As pointed out by @Dellirium, Objects are passed by reference, reqBody is the same object as the data

like image 182
Thalaivar Avatar answered Jun 17 '26 12:06

Thalaivar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!