Reputation: 7708
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?
Upvotes: 2
Views: 1781
Reputation: 422
You need to save data in other variable 1 by 1 object if you want to delete in same way.
Because when you use any object to assign in other object then value assign by reference. for more please check- this link
For your problem solution put values 1 by 1.
Upvotes: 2
Reputation: 23622
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
Upvotes: 6
Reputation: 943150
Is that how delete is supposed to work?
Yes. delete
deletes properties from objects.
… but that isn't where your confusion is coming from.
var data = req.body;
The assignment operator copies the value of req.body
and that value is a reference to an object (JS only ever gives you a reference to an object to play with).
When you copy that reference to data
you have two references pointing to the same object. When you delete a property from the object, it is removed from the object and it doesn't matter which reference to that object you use.
See this question for some information about making a deep copy of an object.
Upvotes: 3
Reputation: 914
Yes it is. Delete keyword deletes the property of the instance itself.
EDIT: Objects are passed by reference. Consider copying the object, so the changes you do will only affect the object you're changing.
Upvotes: 1