Why does the delete operator on the req.user object not work?
let test = new Object(req.user);
console.log(test.password); // Get correct string
delete test.password;
console.log(test.password); // Get correct string, but expect undefined
CodePudding user response:
This works for me
let test = {user:"hello", password:"goodbye"};
console.log(test.password);
// output is: hello
delete test.password;
console.log(test.password);
// output is: undefined
Could you edit post a snippet with an explicit assignment at the top (rather than a reference to req.user, which we can't reproduce). See if the problem reproduces with that.
CodePudding user response:
Use new Object() on an existing object, doesn't actually create a new object. All you get is a reference to the original one.
The original object (req.user) might have the password field as part of it's prototype, and not as an own property. Deleting it from the object does nothing, because it's not a part of the object.
Demo:
const base = Object.create({user:"hello", password:"goodbye"});
const test = new Object(base);
console.log(test === base); // true - it's the same object
console.log({ pass: test.password, ownProp: test.hasOwnProperty('password') });
delete test.password;
console.log({ pass: test.password, ownProp: test.hasOwnProperty('password') });
CodePudding user response:
This line just creates a reference to an existing object:
let test = new Object(req.user);
It's the same thing as
let test = req.user;
So whether or not you can delete test.password depends on whether or not you can delete req.user.password (it's the same operation). If req.user.password is not a writable property, you will get the behavior you describe.
const req = {
user: {}
};
Object.defineProperty(req.user, "password", {
value: "123456",
writable: false
});
let test = new Object(req.user);
console.log(test.password); // Get correct string
delete test.password;
console.log(test.password); // Get correct string, but expect undefined
const req2 = {
user: {
password: "123456"
}
};
let test2 = new Object(req2.user);
console.log(test2.password); // Get correct string
delete test2.password;
console.log(test2.password); // This works as expected
